如何使用NameValuePair在HttpURLConnection中使用POST方法添加参数

277

我正在尝试使用 HttpURLConnection 进行 POST 请求(必须以这种方式使用,无法使用 HttpPost),并且我想要向该连接添加参数,例如:

post.setEntity(new UrlEncodedFormEntity(nvp));

在哪里

nvp = new ArrayList<NameValuePair>();

我有一些数据存储在ArrayList中。我找不到将此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组合的原因是需要不验证证书。虽然这不是问题,它能够很好地将数据发送到服务器。但我需要带参数进行数据发送。
有什么想法吗?

重复免责声明:
在2012年时,我不知道如何将参数插入到HTTP POST请求中。我一直使用NameValuePair,因为它在教程中。这个问题可能看起来像是一个重复,但是我的2012年自己读了那个其他问题,它并没有使用NameValuePair。事实上,它没有解决我的问题。

2
如果您在发布参数方面遇到问题,那么下面的链接可能会对您有所帮助。https://dev59.com/vHE85IYBdhLWcg3wZyqt - Hitendra
1
字符串 url = "http://example.com"; 字符串 charset = "UTF-8"; 字符串 param1 = "value1"; 字符串 param2 = "value2"; // ... 字符串 query = String.format("param1=%s&param2=%s", URLEncoder.encode(param1, charset), URLEncoder.encode(param2, charset)); 你可以使用查询字符串来代替使用NameValuePair列表。 - Hitendra
我需要以这种方式使用它,不能使用HttpPost,这就是为什么我建议使用Manikandan发布的其他答案,它可以正常工作。 - Hitendra
3
可能是Java - sending HTTP parameters via POST method easily的重复问题。 - rogerdpack
1
因为这里的“很多答案”与那个问题的答案相同。但是现在我明白这是一个不同的问题,谢谢澄清 :) - rogerdpack
显示剩余3条评论
16个回答

2
为了使用自定义标头或JSON数据调用POST/PUT/DELETE/GET Restful方法,可以使用以下Async类。
public class HttpUrlConnectionUtlity extends AsyncTask<Integer, Void, String> {
private static final String TAG = "HttpUrlConnectionUtlity";
Context mContext;
public static final int GET_METHOD = 0,
        POST_METHOD = 1,
        PUT_METHOD = 2,
        HEAD_METHOD = 3,
        DELETE_METHOD = 4,
        TRACE_METHOD = 5,
        OPTIONS_METHOD = 6;
HashMap<String, String> headerMap;

String entityString;
String url;
int requestType = -1;
final String timeOut = "TIMED_OUT";

int TIME_OUT = 60 * 1000;

public HttpUrlConnectionUtlity (Context mContext) {
    this.mContext = mContext;
    this.callback = callback;
}

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(Integer... params) {
    int requestType = getRequestType();
    String response = "";
    try {


        URL url = getUrl();
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection = setRequestMethod(urlConnection, requestType);
        urlConnection.setConnectTimeout(TIME_OUT);
        urlConnection.setReadTimeout(TIME_OUT);
        urlConnection.setDoOutput(true);
        urlConnection = setHeaderData(urlConnection);
        urlConnection = setEntity(urlConnection);

        if (urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            response = readResponseStream(urlConnection.getInputStream());
            Logger.v(TAG, response);
        }
        urlConnection.disconnect();
        return response;


    } catch (ProtocolException e) {
        e.printStackTrace();
    } catch (SocketTimeoutException e) {
        return timeOut;
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        Logger.e(TAG, "ALREADY CONNECTED");
    }
    return response;
}

@Override
protected void onPostExecute(String response) {
    super.onPostExecute(response);

    if (TextUtils.isEmpty(response)) {
        //empty response
    } else if (response != null && response.equals(timeOut)) {
        //request timed out 
    } else    {
    //process your response
   }
}


private String getEntityString() {
    return entityString;
}

public void setEntityString(String s) {
    this.entityString = s;
}

private String readResponseStream(InputStream in) {
    BufferedReader reader = null;
    StringBuffer response = new StringBuffer();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return response.toString();
}

private HttpURLConnection setEntity(HttpURLConnection urlConnection) throws IOException {
    if (getEntityString() != null) {
        OutputStream outputStream = urlConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
        writer.write(getEntityString());
        writer.flush();
        writer.close();
        outputStream.close();
    } else {
        Logger.w(TAG, "NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND ||NO ENTITY DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setHeaderData(HttpURLConnection urlConnection) throws UnsupportedEncodingException {
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setRequestProperty("Accept", "application/json");
    if (getHeaderMap() != null) {
        for (Map.Entry<String, String> entry : getHeaderMap().entrySet()) {
            urlConnection.setRequestProperty(entry.getKey(), entry.getValue());
        }
    } else {
        Logger.w(TAG, "NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND ||NO HEADER DATA TO APPEND");
    }
    return urlConnection;
}

private HttpURLConnection setRequestMethod(HttpURLConnection urlConnection, int requestMethod) {
    try {
        switch (requestMethod) {
            case GET_METHOD:
                urlConnection.setRequestMethod("GET");
                break;
            case POST_METHOD:
                urlConnection.setRequestMethod("POST");
                break;
            case PUT_METHOD:
                urlConnection.setRequestMethod("PUT");
                break;
            case DELETE_METHOD:
                urlConnection.setRequestMethod("DELETE");
                break;
            case OPTIONS_METHOD:
                urlConnection.setRequestMethod("OPTIONS");
                break;
            case HEAD_METHOD:
                urlConnection.setRequestMethod("HEAD");
                break;
            case TRACE_METHOD:
                urlConnection.setRequestMethod("TRACE");
                break;
        }
    } catch (ProtocolException e) {
        e.printStackTrace();
    }
    return urlConnection;
}

public int getRequestType() {
    return requestType;
}

public void setRequestType(int requestType) {
    this.requestType = requestType;
}

public URL getUrl() throws MalformedURLException {
    return new URL(url);
}

public void setUrl(String url) {
    this.url = url;
}

public HashMap<String, String> getHeaderMap() {
    return headerMap;
}

public void setHeaderMap(HashMap<String, String> headerMap) {
    this.headerMap = headerMap;
}   }

使用方法如下:

    HttpUrlConnectionUtlity httpMethod = new HttpUrlConnectionUtlity (mContext);
    JSONObject jsonEntity = new JSONObject();

    try {
        jsonEntity.put("key1", value1);
        jsonEntity.put("key2", value2);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    httpMethod.setUrl(YOUR_URL_STRING);
    HashMap<String, String> headerMap = new HashMap<>();
    headerMap.put("key",value);
    headerMap.put("key1",value1);
    httpMethod.setHeaderMap(headerMap);
    httpMethod.setRequestType(WiseConnectHttpMethod.POST_METHOD); //specify POST/GET/DELETE/PUT
    httpMethod.setEntityString(jsonEntity.toString());
    httpMethod.execute();

2
在我的情况下,我创建了这样一个函数来进行Post请求,它接受字符串类型的url和参数哈希表。
 public  String postRequest( String mainUrl,HashMap<String,String> parameterList)
{
    String response="";
    try {
        URL url = new URL(mainUrl);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : parameterList.entrySet())
        {
            if (postData.length() != 0) postData.append('&');
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }

        byte[] postDataBytes = postData.toString().getBytes("UTF-8");




        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
        conn.setDoOutput(true);
        conn.getOutputStream().write(postDataBytes);

        Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

        StringBuilder sb = new StringBuilder();
        for (int c; (c = in.read()) >= 0; )
            sb.append((char) c);
        response = sb.toString();


    return  response;
    }catch (Exception excep){
        excep.printStackTrace();}
    return response;
}

1
通过使用org.apache.http.client.HttpClient,您可以更易读地以以下方式完成此操作。
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.yoursite.com/script.php");

在 try catch 中,您可以插入

// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("id", "12345"));
nameValuePairs.add(new BasicNameValuePair("stringdata", "AndDev is Cool!"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);

1
谢谢你的回复!但是我不能按照这种方式使用(问题中已经说明,第一行)。 - Michal
7
这不是这个问题的恰当答案。 - Skynet
3
NameValuePair在Api 22已被弃用,请查看我的答案https://dev59.com/0Gkw5IYBdhLWcg3wm70h#29561084 - Fahim
1
即使是HTTP客户端也在API 23中被弃用和移除了。 - RevanthKrishnaKumar V.

1
使用NameValuePair和OutPut对HttpURLConnection进行POST请求的参数。
        try {
        URL url = new URL("https://yourUrl.com");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestMethod("POST");

        conn.setRequestProperty("Content-Type", "application/json");

        JSONObject data = new JSONObject();
        data.put("key1", "value1");
        data.put("key2", "value2");

        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(data.toString());
        wr.flush();
        wr.close();

        BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        System.out.println(response.toString());
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

0
我使用类似这样的东西:
SchemeRegistry sR = new SchemeRegistry();
sR.register(new Scheme("https", SSLSocketFactory.getSocketFactory(), 443));

HttpParams params = new BasicHttpParams();
SingleClientConnManager mgr = new SingleClientConnManager(params, sR);

HttpClient httpclient = new DefaultHttpClient(mgr, params);

HttpPost httppost = new HttpPost(url);
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

HttpResponse response = httpclient.execute(httppost);

-1
JSONObject params = new JSONObject();
try {
   params.put(key, val);
}catch (JSONException e){
   e.printStackTrace();
}

这是我如何通过POST传递“params”(JSONObject)的方法

connection.getOutputStream().write(params.toString().getBytes("UTF-8"));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接