Java – 通过POST方法轻松发送HTTP参数
我成功地使用这个代码通过GET
方法发送一些参数的HTTP
请求
function void sendRequest(String request) { // ie: request = "http://example.com/index.php?param1=a¶m2=b¶m3=c"; URL url = new URL(request); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("GET"); connection.setRequestProperty("Content-Type", "text/plain"); connection.setRequestProperty("charset", "utf-8"); connection.connect(); }
现在我可能需要通过POST
方法发送参数(即param1,param2,param3),因为它们很长。 我想为该方法添加一个额外的参数(即stringhttpMethod)。
我怎样才能改变上面的代码尽可能less能够通过GET
或POST
发送参数?
我希望改变
connection.setRequestMethod("GET");
至
connection.setRequestMethod("POST");
会做的伎俩,但参数仍然通过GET方法发送。
HttpURLConnection
有任何方法可以帮助吗? 有没有什么有用的Java构造?
任何帮助将非常感激。
在GET请求中,参数作为URL的一部分发送。
在POST请求中,这些参数作为请求的主体,在标题之后发送。
要使用HttpURLConnection执行POST,需要在打开连接后将参数写入连接。
这段代码应该让你开始:
String urlParameters = "param1=a¶m2=b¶m3=c"; byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 ); int postDataLength = postData.length; String request = "http://example.com/index.php"; URL url = new URL( request ); HttpURLConnection conn= (HttpURLConnection) url.openConnection(); conn.setDoOutput( true ); conn.setInstanceFollowRedirects( false ); conn.setRequestMethod( "POST" ); conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded"); conn.setRequestProperty( "charset", "utf-8"); conn.setRequestProperty( "Content-Length", Integer.toString( postDataLength )); conn.setUseCaches( false ); try( DataOutputStream wr = new DataOutputStream( conn.getOutputStream())) { wr.write( postData ); }
下面是一个简单的例子,提交表单然后将结果页面转储到System.out
。 当然,请根据需要更改url和POST参数:
import java.io.*; import java.net.*; import java.util.*; class Test { public static void main(String[] args) throws Exception { URL url = new URL("http://example.net/new-message.php"); Map<String,Object> params = new LinkedHashMap<>(); params.put("name", "Freddie the Fish"); params.put("email", "fishie@seamail.example.com"); params.put("reply_to_thread", 10394); params.put("message", "Shark attacks in Botany Bay have gotten out of control. We need more defensive dolphins to protect the schools here, but Mayor Porpoise is too busy stuffing his snout with lobsters. He's so shellfish."); StringBuilder postData = new StringBuilder(); for (Map.Entry<String,Object> param : params.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")); for (int c; (c = in.read()) >= 0;) System.out.print((char)c); } }
如果你想把结果作为一个String
而不是直接打印出来的话:
StringBuilder sb = new StringBuilder(); for (int c; (c = in.read()) >= 0;) sb.append((char)c); String response = sb.toString();
我无法得到艾伦的榜样 ,所以我最终这样做了:
String urlParameters = "param1=a¶m2=b¶m3=c"; URL url = new URL("http://example.com/index.php"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { System.out.println(line); } writer.close(); reader.close();
我觉得HttpURLConnection
真的很麻烦。 而且你必须编写大量的样板,容易出错的代码。 我需要一个轻量级的包装器为我的Android项目,并出来一个库,你也可以使用: DavidWebb 。
上面的例子可以这样写:
Webb webb = Webb.create(); webb.post("http://example.com/index.php") .param("param1", "a") .param("param2", "b") .param("param3", "c") .ensureSuccess() .asVoid();
您可以在提供的链接中find备用库列表。
我看到其他答案已经给出了替代scheme,我个人认为,直观地说,你做的是正确的事情;)。 对不起,在devoxx有几个发言者一直在咆哮这类事情。
这就是为什么我个人使用Apache的HTTPClient / HttpCore库来完成这种工作,我发现他们的API比Java的本地HTTP支持更容易使用。 YMMV当然!
import java.net.*; public class demo{ public static void main(){ String Data = "data=Hello+World!"; URL url = new URL("http://localhost:8084/WebListenerServer/webListener"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("POST"); con.setDoOutput(true); con.getOutputStream().write(Data.getBytes("UTF-8")); con.getInputStream(); } }
我已阅读上面的答案,并已创build一个实用工具类来简化HTTP请求。 我希望它能帮助你。
方法调用
// send params with Hash Map HashMap<String, String> params = new HashMap<String, String>(); params.put("email","me@example.com"); params.put("password","12345"); //server url String url = "http://www.example.com"; // static class "HttpUtility" with static method "newRequest(url,method,callback)" HttpUtility.newRequest(url,HttpUtility.METHOD_POST,params, new HttpUtility.Callback() { @Override public void OnSuccess(String response) { // on success System.out.println("Server OnSuccess response="+response); } @Override public void OnError(int status_code, String message) { // on error System.out.println("Server OnError status_code="+status_code+" message="+message); } });
实用程序类
import java.io.*; import java.net.*; import java.util.HashMap; import java.util.Map; import static java.net.HttpURLConnection.HTTP_OK; public class HttpUtility { public static final int METHOD_GET = 0; // METHOD GET public static final int METHOD_POST = 1; // METHOD POST // Callback interface public interface Callback { // abstract methods public void OnSuccess(String response); public void OnError(int status_code, String message); } // static method public static void newRequest(String web_url, int method, HashMap < String, String > params, Callback callback) { // thread for handling async task new Thread(new Runnable() { @Override public void run() { try { String url = web_url; // write GET params,append with url if (method == METHOD_GET && params != null) { for (Map.Entry < String, String > item: params.entrySet()) { String key = URLEncoder.encode(item.getKey(), "UTF-8"); String value = URLEncoder.encode(item.getValue(), "UTF-8"); if (!url.contains("?")) { url += "?" + key + "=" + value; } else { url += "&" + key + "=" + value; } } } HttpURLConnection urlConnection = (HttpURLConnection) new URL(url).openConnection(); urlConnection.setDoOutput(true); // write POST params urlConnection.setUseCaches(false); urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); // handle url encoded form data urlConnection.setRequestProperty("charset", "utf-8"); if (method == METHOD_GET) { urlConnection.setRequestMethod("GET"); } else if (method == METHOD_POST) { urlConnection.setRequestMethod("POST"); } //write POST data if (method == METHOD_POST && params != null) { StringBuilder postData = new StringBuilder(); for (Map.Entry < String, String > item: params.entrySet()) { if (postData.length() != 0) postData.append('&'); postData.append(URLEncoder.encode(item.getKey(), "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(item.getValue()), "UTF-8")); } byte[] postDataBytes = postData.toString().getBytes("UTF-8"); urlConnection.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length)); urlConnection.getOutputStream().write(postDataBytes); } // server response code int responseCode = urlConnection.getResponseCode(); if (responseCode == HTTP_OK && callback != null) { BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { response.append(line); } // callback success callback.OnSuccess(response.toString()); reader.close(); // close BufferReader } else if (callback != null) { // callback error callback.OnError(responseCode, urlConnection.getResponseMessage()); } urlConnection.disconnect(); // disconnect connection } catch (IOException e) { e.printStackTrace(); if (callback != null) { // callback error callback.OnError(500, e.getLocalizedMessage()); } } } }).start(); // start thread } }
我遇到过同样的问题。 我想通过POST发送数据。 我使用了下面的代码:
URL url = new URL("http://example.com/getval.php"); Map<String,Object> params = new LinkedHashMap<>(); params.put("param1", param1); params.put("param2", param2); StringBuilder postData = new StringBuilder(); for (Map.Entry<String,Object> param : params.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")); } String urlParameters = postData.toString(); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); String result = ""; String line; BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); while ((line = reader.readLine()) != null) { result += line; } writer.close(); reader.close() System.out.println(result);
我用Jsoup进行分析:
Document doc = Jsoup.parseBodyFragment(value); Iterator<Element> opts = doc.select("option").iterator(); for (;opts.hasNext();) { Element item = opts.next(); if (item.hasAttr("value")) { System.out.println(item.attr("value")); } }
试试这个模式:
public static PricesResponse getResponse(EventRequestRaw request) { // String urlParameters = "param1=a¶m2=b¶m3=c"; String urlParameters = Piping.serialize(request); HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters); PricesResponse response = null; try { // POST OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream()); writer.write(urlParameters); writer.flush(); // RESPONSE BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8)); String json = Buffering.getString(reader); response = (PricesResponse) Piping.deserialize(json, PricesResponse.class); writer.close(); reader.close(); } catch (Exception e) { e.printStackTrace(); } conn.disconnect(); System.out.println("PricesClient: " + response.toString()); return response; } public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) { return RestClient.getConnection(endPoint, "POST", urlParameters); } public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) { System.out.println("ENDPOINT " + endPoint + " METHOD " + method); HttpURLConnection conn = null; try { URL url = new URL(endPoint); conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod(method); conn.setDoOutput(true); conn.setRequestProperty("Content-Type", "text/plain"); } catch (IOException e) { e.printStackTrace(); } return conn; }
在这里我把jsonobject作为参数// jsonobject = {“name”:“lucifer”,“pass”:“abc”} // serverUrl =“ http://192.168.100.12/testing ”//host=192.168.100.12
public static String getJson(String serverUrl,String host,String jsonobject){ StringBuilder sb = new StringBuilder(); String http = serverUrl; HttpURLConnection urlConnection = null; try { URL url = new URL(http); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setDoOutput(true); urlConnection.setRequestMethod("POST"); urlConnection.setUseCaches(false); urlConnection.setConnectTimeout(50000); urlConnection.setReadTimeout(50000); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestProperty("Host", host); urlConnection.connect(); //You Can also Create JSONObject here OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); out.write(jsonobject);// here i sent the parameter out.close(); int HttpResult = urlConnection.getResponseCode(); if (HttpResult == HttpURLConnection.HTTP_OK) { BufferedReader br = new BufferedReader(new InputStreamReader( urlConnection.getInputStream(), "utf-8")); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.e("new Test", "" + sb.toString()); return sb.toString(); } else { Log.e(" ", "" + urlConnection.getResponseMessage()); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } finally { if (urlConnection != null) urlConnection.disconnect(); } return null; }
你好请使用这个类来改进你的post方法
public static JSONObject doPostRequest(HashMap<String, String> data, String url) { try { RequestBody requestBody; MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM); if (data != null) { for (String key : data.keySet()) { String value = data.get(key); Utility.printLog("Key Values", key + "-----------------" + value); mBuilder.addFormDataPart(key, value); } } else { mBuilder.addFormDataPart("temp", "temp"); } requestBody = mBuilder.build(); Request request = new Request.Builder() .url(url) .post(requestBody) .build(); OkHttpClient client = new OkHttpClient(); Response response = client.newCall(request).execute(); String responseBody = response.body().string(); Utility.printLog("URL", url); Utility.printLog("Response", responseBody); return new JSONObject(responseBody); } catch (UnknownHostException | UnsupportedEncodingException e) { JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Error: " + e.getLocalizedMessage()); } catch (Exception e) { e.printStackTrace(); JSONObject jsonObject=new JSONObject(); try { jsonObject.put("status","false"); jsonObject.put("message",e.getLocalizedMessage()); } catch (JSONException e1) { e1.printStackTrace(); } Log.e(TAG, "Other Error: " + e.getLocalizedMessage()); } return null; }
我接受了Boann的答案,并使用它来创build一个更灵活的查询string生成器,它支持列表和数组,就像php的http_build_query方法一样:
public static byte[] httpBuildQueryString(Map<String, Object> postsData) throws UnsupportedEncodingException { StringBuilder postData = new StringBuilder(); for (Map.Entry<String,Object> param : postsData.entrySet()) { if (postData.length() != 0) postData.append('&'); Object value = param.getValue(); String key = param.getKey(); if(value instanceof Object[] || value instanceof List<?>) { int size = value instanceof Object[] ? ((Object[])value).length : ((List<?>)value).size(); for(int i = 0; i < size; i++) { Object val = value instanceof Object[] ? ((Object[])value)[i] : ((List<?>)value).get(i); if(i>0) postData.append('&'); postData.append(URLEncoder.encode(key + "[" + i + "]", "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(val), "UTF-8")); } } else { postData.append(URLEncoder.encode(key, "UTF-8")); postData.append('='); postData.append(URLEncoder.encode(String.valueOf(value), "UTF-8")); } } return postData.toString().getBytes("UTF-8"); }
我build议在http api上build立http请求 。
对于你的情况,你可以看到例子:
private static final HttpRequest<String.class> HTTP_REQUEST = HttpRequestBuilder.createPost("http://example.com/index.php", String.class) .responseDeserializer(ResponseDeserializer.ignorableDeserializer()) .build(); public void sendRequest(String request){ String parameters = request.split("\\?")[1]; ResponseHandler<String> responseHandler = HTTP_REQUEST.executeWithQuery(parameters); System.out.println(responseHandler.getStatusCode()); System.out.println(responseHandler.get()); //prints response body }
如果你对响应主体不感兴趣
private static final HttpRequest<?> HTTP_REQUEST = HttpRequestBuilder.createPost("http://example.com/index.php").build(); public void sendRequest(String request){ ResponseHandler<String> responseHandler = HTTP_REQUEST.executeWithQuery(parameters); }
对于一般发送POST请求与HTTP请求 :阅读文档,并看到我的答案HTTP POST请求与JSONstring在JAVA , 发送HTTP POST请求在Java中 , 使用 Java中的HTTP HTTP POST
看来你还必须调用connection.getOutputStream()
“至less一次”(以及setDoOutput(true)
),以便将其视为POST。
所以最低要求的代码是:
URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //connection.setRequestMethod("POST"); this doesn't seem to do anything at all..so not useful connection.setDoOutput(true); // set it to POST...not enough by itself however, also need the getOutputStream call... connection.connect(); connection.getOutputStream().close();
你甚至可以在urlString中使用“GET”风格的参数。 虽然这可能会混淆事物。