我正在try 用HttpURLConnection来做POST(我需要这样使用,不能使用HttpPost),并且我想向该连接添加参数,如下所示

post.setEntity(new UrlEncodedFormEntity(nvp));

哪里

nvp = new ArrayList<NameValuePair>();

有一些数据存储在数据库中.我找不到一种方法,如何将这ArrayList个添加到我的HttpURLConnection中:

HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
http.setRequestMethod("POST");
http.setDoInput(true);
http.setDoOutput(true);

这种尴尬的https和http组合的原因是需要not verifying个证书.不过,这不是问题,它可以很好地发布服务器.但我需要它来发表论点.

有什么 idea 吗?


Duplicate Disclaimer:

回到2012年,我不知道参数是如何插入到HTTP POST请求中的.我一直在关注NameValuePair,因为它在一个教程中.这个问题可能看起来像是重复的,然而,我2012年的self 阅读了100个问题,结果是NOT个用NameValuePair.事实上,这并没有解决我的问题.

推荐答案

您可以获取连接的输出流,并将参数查询字符串写入其中.

URL url = new URL("http://yoururl.com");
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);

List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("firstParam", paramValue1));
params.add(new BasicNameValuePair("secondParam", paramValue2));
params.add(new BasicNameValuePair("thirdParam", paramValue3));

OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
        new OutputStreamWriter(os, "UTF-8"));
writer.write(getQuery(params));
writer.flush();
writer.close();
os.close();

conn.connect();

...

private String getQuery(List<NameValuePair> params) throws UnsupportedEncodingException
{
    StringBuilder result = new StringBuilder();
    boolean first = true;

    for (NameValuePair pair : params)
    {
        if (first)
            first = false;
        else
            result.append("&");

        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
    }

    return result.toString();
}

Android相关问答推荐

打开平板电脑的下载文件夹中的文件,例如使用其mimeType将Intent发送到我们的应用程序

如何在点击按钮时将字符串插入到文本字段中的光标位置?

显示本地房间数据库中未保存的项目的动态列表

替换- prop -中的值(adb shell getprop)

如何在Jetpack导航中不显示目的地?

StateFlow集合AsState没有更新他的值Jetpack Compose导航

LocalContext.current的问题(@Composable调用只能从@Composable函数的上下文发生)

无法加载类';com.android.build.api.extension.AndroidComponentsExtension';

如果我的圆形图像的顶部居中于卡片内部,我如何在其下方画一条弧线?

弹出导航堆栈后,Compose 无法访问 Hilt View Model

kotlin中&&和and的区别

如何禁用自动登录 google play games services android unity?

setContentView() 方法的签名

DatePickerDialog (Android/Kotlin) 的两个问题

我的观点在jetpack compose中相互重叠

自定义 Recyclerview [Android & Kotlin]

获取模板向导配方类 Intellij 中的应用程序包名称

清洁架构中的服务

这是 let 函数的正确用法吗?

复用 RecyclerView 适配器,避免不必要的 API 调用