如何使用NameValuePair使用POST将参数添加到HttpURLConnection


257

我试图做POSTHttpURLConnection(我需要使用这种方式,不能使用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组合的原因是不需要验证证书。但这不是问题,它可以很好地发布服务器。但是我需要它来发布参数。

有任何想法吗?


重复免责声明:

早在2012年,我还不知道如何将参数插入到HTTP POST请求中。我一直坚持下去,NameValuePair因为它在教程中。这个问题似乎有点重复,但是,我2012年的自我读过另一个问题,但没有使用NameValuePair。实际上,它并不能解决我的问题。


2
如果您在发布参数方面遇到问题,则下面的链接可能会对您有所帮助。stackoverflow.com/questions/2793150/…–
Hitendra 2012年

1
字符串url =“ example.com ”; 字符串字符集=“ UTF-8”; 字符串param1 =“ value1”; 字符串param2 =“ value2”; // ...字符串查询= String.format(“ param1 =%s&param2 =%s”,URLEncoder.encode(param1,charset),URLEncoder.encode(param2,charset)); 您可以创建查询字符串,而不使用NameValuePair List。
希滕德拉2012年

“我需要以这种方式使用它,不能使用HttpPost”,这就是为什么我建议Manikandan发布的其他答案可以正常工作的原因。
希滕德拉2012年


1
这是因为这里的“许多答案”与该问题的答案相同。但现在我看到这是一个不同的问题,感谢您的澄清:)
rogerdpack

Answers:


362

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

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();
}

25
NameValuePair也可以用AbstractMap的SimpleEntry代替。参见本页:stackoverflow.com/questions/2973041/a-keyvaluepair-in-java

如果不确定,这是进口商品。导入org.apache.http.NameValuePair; 导入org.apache.http.message.BasicNameValuePair;
WoodenKitty 2014年

9
为了获得最佳性能,您应该预先知道主体长度时调用setFixedLengthStreamingMode(int),否则不调用setChunkedStreamingMode(int)。否则,HttpURLConnection将被迫在传输之前在内存中缓冲整个请求主体,从而浪费(并可能耗尽)堆并增加延迟。
Muhammad Babar 2014年

11
NameValuePair在Api 22中已弃用,请检查我的答案stackoverflow.com/a/29561084/4552938
Fahim 2015年

1
也许在构建URL对象时可以使用原始模式,如下所示:URL url = new URL("http://yoururl.com?k1=v1&k2=v2&···&kn=vn");然后将conn设置为使用POST方法时,无需编写它们。
alexscmar

184

由于不推荐使用NameValuePair。想共享我的代码

public String  performPostCall(String requestURL,
            HashMap<String, String> postDataParams) {

        URL url;
        String response = "";
        try {
            url = new URL(requestURL);

            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(15000);
            conn.setConnectTimeout(15000);
            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);


            OutputStream os = conn.getOutputStream();
            BufferedWriter writer = new BufferedWriter(
                    new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(postDataParams));

            writer.flush();
            writer.close();
            os.close();
            int responseCode=conn.getResponseCode();

            if (responseCode == HttpsURLConnection.HTTP_OK) {
                String line;
                BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                while ((line=br.readLine()) != null) {
                    response+=line;
                }
            }
            else {
                response="";

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

....

  private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
        StringBuilder result = new StringBuilder();
        boolean first = true;
        for(Map.Entry<String, String> entry : params.entrySet()){
            if (first)
                first = false;
            else
                result.append("&");

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

        return result.toString();
    }

10
感谢您保持最新状态Fahim :-)
Michal

3
如果您的compileSdkVersion为23(棉花糖),则您将无法再使用NameValuePair,因为他们删除了该库。我担心迁移会很痛苦,但是您的解决方案为我节省了很多时间。谢谢。
挑战

效果很好,但是为什么响应中有双引号""result""呢?
Apostrofix

1
你们是否有OutputStream os = conn.getOutputStream();果冻豆上的这一行有问题,原因是没有与主机名关联的地址?
里卡多

1
感谢您分享您的代码。甚至Android开发人员网站也没有提供解决方案。
Ahsan

153

如果不需要ArrayList<NameValuePair>for参数,这是一个较短的解决方案,它使用Uri.Builder该类构建查询字符串:

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);

Uri.Builder builder = new Uri.Builder()
        .appendQueryParameter("firstParam", paramValue1)
        .appendQueryParameter("secondParam", paramValue2)
        .appendQueryParameter("thirdParam", paramValue3);
String query = builder.build().getEncodedQuery();

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

conn.connect();

7
这应该是一个答案,因为不必重新发明轮子!
注射器

如何在appendqueryparameter中上传图像和所有文件的主体
Harsha

2
更令人满意的解决方案
PYPL,2016年

@mpolci,对于复杂类型的参数,我有疑问/疑问。我有参数,而且我不知道如何传递这些参数。{“ key1”:“ value1”,“ key2”:“ value2”,“ key3”:{“内部键1”:“内部值1”,“内部密钥2”:“内部值2”}}。已经为我提供了这种类型的复杂键值参数,我想知道如何在Web服务中传递这些参数?
克鲁斯

1
@Krups我认为您的问题与此不同,请尝试查找使用POST发送JSON对象
mpolci,2016年

25

一种解决方案是使自己的params字符串。

这是我在最新项目中一直使用的实际方法。您需要将参数从哈希表更改为namevaluepair的:

private static String getPostParamString(Hashtable<String, String> params) {
    if(params.size() == 0)
        return "";

    StringBuffer buf = new StringBuffer();
    Enumeration<String> keys = params.keys();
    while(keys.hasMoreElements()) {
        buf.append(buf.length() == 0 ? "" : "&");
        String key = keys.nextElement();
        buf.append(key).append("=").append(params.get(key));
    }
    return buf.toString();
}

发布参数:

OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(getPostParamString(req.getPostParams()));

3
当然,您应该对键值对进行编码
Max Nanasy 2015年

14

我想我找到了您所需要的。它可能会帮助别人。

您可以使用方法UrlEncodedFormEntity.writeTo(OutputStream)

UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nvp); 
http.connect();

OutputStream output = null;
try {
  output = http.getOutputStream();    
  formEntity.writeTo(output);
} finally {
 if (output != null) try { output.close(); } catch (IOException ioe) {}
}

14

接受的答案在以下位置引发ProtocolException:

OutputStream os = conn.getOutputStream();

因为它不会启用URLConnection对象的输出。解决方案应包括以下内容:

conn.setDoOutput(true);

使它工作。


13

如果还不算太晚,我想分享我的代码

Utils.java:

public static String buildPostParameters(Object content) {
        String output = null;
        if ((content instanceof String) ||
                (content instanceof JSONObject) ||
                (content instanceof JSONArray)) {
            output = content.toString();
        } else if (content instanceof Map) {
            Uri.Builder builder = new Uri.Builder();
            HashMap hashMap = (HashMap) content;
            if (hashMap != null) {
                Iterator entries = hashMap.entrySet().iterator();
                while (entries.hasNext()) {
                    Map.Entry entry = (Map.Entry) entries.next();
                    builder.appendQueryParameter(entry.getKey().toString(), entry.getValue().toString());
                    entries.remove(); // avoids a ConcurrentModificationException
                }
                output = builder.build().getEncodedQuery();
            }
        }

        return output;
    }

public static URLConnection makeRequest(String method, String apiAddress, String accessToken, String mimeType, String requestBody) throws IOException {
        URL url = new URL(apiAddress);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(!method.equals("GET"));
        urlConnection.setRequestMethod(method);

        urlConnection.setRequestProperty("Authorization", "Bearer " + accessToken);        

        urlConnection.setRequestProperty("Content-Type", mimeType);
        OutputStream outputStream = new BufferedOutputStream(urlConnection.getOutputStream());
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "utf-8"));
        writer.write(requestBody);
        writer.flush();
        writer.close();
        outputStream.close();            

        urlConnection.connect();

        return urlConnection;
    }

MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    new APIRequest().execute();
}

private class APIRequest extends AsyncTask<Void, Void, String> {

        @Override
        protected Object doInBackground(Void... params) {

            // Of course, you should comment the other CASES when testing one CASE

            // CASE 1: For FromBody parameter
            String url = "http://10.0.2.2/api/frombody";
            String requestBody = Utils.buildPostParameters("'FromBody Value'"); // must have '' for FromBody parameter
            HttpURLConnection urlConnection = null;
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                InputStream inputStream;
                // get stream
                if (urlConnection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {
                    inputStream = urlConnection.getInputStream();
                } else {
                    inputStream = urlConnection.getErrorStream();
                }
                // parse stream
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                String temp, response = "";
                while ((temp = bufferedReader.readLine()) != null) {
                    response += temp;
                }
                return response;
            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }

            // CASE 2: For JSONObject parameter
            String url = "http://10.0.2.2/api/testjsonobject";
            JSONObject jsonBody;
            String requestBody;
            HttpURLConnection urlConnection;
            try {
                jsonBody = new JSONObject();
                jsonBody.put("Title", "BNK Title");
                jsonBody.put("Author", "BNK");
                jsonBody.put("Date", "2015/08/08");
                requestBody = Utils.buildPostParameters(jsonBody);
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/json", requestBody);                    
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (JSONException | IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }           

            // CASE 3: For form-urlencoded parameter
            String url = "http://10.0.2.2/api/token";
            HttpURLConnection urlConnection;
            Map<String, String> stringMap = new HashMap<>();
            stringMap.put("grant_type", "password");
            stringMap.put("username", "username");
            stringMap.put("password", "password");
            String requestBody = Utils.buildPostParameters(stringMap);
            try {
                urlConnection = (HttpURLConnection) Utils.makeRequest("POST", url, null, "application/x-www-form-urlencoded", requestBody);
                ...
                // the same logic to case #1
                ...
                return response;
            } catch (Exception e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
            }                  
        }

        @Override
        protected void onPostExecute(String response) {
            super.onPostExecute(response);
            // do something...
        }
    }

@Srinivasan,正如您在我的代码中看到的:“ if(urlConnection.getResponseCode()== HttpURLConnection.HTTP_OK){...} else {...}”
BNK 2015年

是的,我已经知道了,但是我问的是,哪个变量将完全响应给定的网址
iSrinivasan27,2015年

1
@Srinivasan更详细的信息,您可以尝试InputStream inputStream = null; 如果(urlConnection.getResponseCode()== HttpURLConnection.HTTP_OK){inputStream = urlConnection.getInputStream(); } else {inputStream = urlConnection.getErrorStream(); }
BNK 2015年

@Srinivasan实际上,如果响应代码<400(错误请求),则使用getInputStream,如果> = 400,则使用getErrorStream
BNK 2015年

1
超级材料兄弟的好榜样

10

使用PrintWriter有一种简单得多的方法(请参阅此处

基本上,您需要做的是:

// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// write out form parameters
String postParamaters = "param1=value1&param2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

// connect
urlConnection.connect();

4

AsyncTaskJSONObect通过POST方法发送数据

public class PostMethodDemo extends AsyncTask<String , Void ,String> {
        String server_response;

        @Override
        protected String doInBackground(String... strings) {
            URL url;
            HttpURLConnection urlConnection = null;

            try {
                url = new URL(strings[0]);
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setDoOutput(true);
                urlConnection.setDoInput(true);
                urlConnection.setRequestMethod("POST");

                DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream ());

                try {
                    JSONObject obj = new JSONObject();
                    obj.put("key1" , "value1");
                    obj.put("key2" , "value2");

                    wr.writeBytes(obj.toString());
                    Log.e("JSON Input", obj.toString());
                    wr.flush();
                    wr.close();
                } catch (JSONException ex) {
                    ex.printStackTrace();
                }
                urlConnection.connect();

                int responseCode = urlConnection.getResponseCode();

                if(responseCode == HttpURLConnection.HTTP_OK){
                    server_response = readStream(urlConnection.getInputStream());
                }

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            Log.e("Response", "" + server_response);
        }
    }

    public static String readStream(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();
    }

3

试试这个:

HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("your url");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("user_name", "Name"));
nameValuePairs.add(new BasicNameValuePair("pass","Password" ));
nameValuePairs.add(new BasicNameValuePair("user_email","email" ));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

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

String ret = EntityUtils.toString(response.getEntity());
Log.v("Util response", ret);

您可以nameValuePairs根据需要添加任意数量。并且不要忘记在列表中提及计数。


请参阅此链接。xyzws.com/Javafaq/…–
Manikandan

1
这不能回答标题为“ How to add parameters to HttpURLConnection using POST-误导”的问题。
User3

2
这不是对该问题的正确答案。
天网2015年

1
NameValuePair在Api 22中已弃用,请检查我的答案stackoverflow.com/a/29561084/4552938
Fahim 2015年

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();

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)2012年

7
这不是对该问题的正确答案。
天网2015年

3
NameValuePair在Api 22中已弃用,请检查我的答案stackoverflow.com/a/29561084/4552938
Fahim 2015年

1
即使HTTP客户端也已过时,去除API 23
RevanthKrishnaKumar五,

0

就我而言,我创建了这样的函数来发出Post请求,该请求接受String url和参数的hashmap

 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;
}

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传递“参数”(JSONObject)的方式

connection.getOutputStream().write(params.toString().getBytes("UTF-8"));
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.