我想在Java中使用JSON進行簡單的HTTP POST。在Java中使用JSON的HTTP POST
假設URL是www.site.com
,它需要在標註爲'details'
例如價值{"name":"myname","age":"20"}
。
我該如何去創建POST的語法?
我也無法在JSON Javadoc中找到POST方法。
我想在Java中使用JSON進行簡單的HTTP POST。在Java中使用JSON的HTTP POST
假設URL是www.site.com
,它需要在標註爲'details'
例如價值{"name":"myname","age":"20"}
。
我該如何去創建POST的語法?
我也無法在JSON Javadoc中找到POST方法。
這可能是最容易使用的HttpURLConnection。
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
您將使用的JSONObject或什麼來構建你的JSON,但不處理網絡;你需要序列化它,然後將它傳遞給HttpURLConnection以POST。
以下是你需要做的:
釷E碼大致樣子(你仍需要調試它,讓它工作)
//Deprecated
//HttpClient httpClient = new DefaultHttpClient();
HttpClient httpClient = HttpClientBuilder.create().build(); //Use this instead
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/x-www-form-urlencoded");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
//handle response here...
}catch (Exception ex) {
//handle exception here
} finally {
//Deprecated
//httpClient.getConnectionManager().shutdown();
}
@ MOMO的回答爲Apache HttpClient的,版本4.3.1或更高版本。我使用JSON-Java
建立我的JSON對象:
JSONObject json = new JSONObject();
json.put("someKey", "someValue");
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params = new StringEntity(json.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
} catch (Exception ex) {
// handle exception here
} finally {
httpClient.close();
}
謝謝,但不是「application/x-www-form-urlencoded」,內容類型應該是「應用程序/ json」! –
您可以使用GSON庫到您的Java類轉換成JSON對象。
創建要發送 按照以上示例
{"name":"myname","age":"20"}
成爲
class pojo1
{
String name;
String age;
//generate setter and getters
}
一旦你設置pojo1類中的變量,你可以給變量一個POJO類,使用下面的代碼
String postUrl = "www.site.com";// put in your url
Gson gson = new Gson();
HttpClient httpClient = HttpClientBuilder.create().build();
HttpPost post = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse response = httpClient.execute(post);
這些都是進口
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;
和GSON
import com.google.gson.Gson;
嗨,你如何創建你的httpClient對象?這是一個接口 – user3290180
是的,這是一個接口。您可以使用'HttpClient httpClient = new DefaultHttpClient()'創建一個實例;'' – Prakash
現在已經棄用了,我們必須使用HttpClient httpClient = HttpClientBuilder.create()。build(); – user3290180
試試這個代碼:
HttpClient httpClient = new DefaultHttpClient();
try {
HttpPost request = new HttpPost("http://yoururl");
StringEntity params =new StringEntity("details={\"name\":\"myname\",\"age\":\"20\"} ");
request.addHeader("content-type", "application/json");
request.addHeader("Accept","application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
// handle response here...
}catch (Exception ex) {
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
我發現這個問題,尋找有關如何從Java客戶端發送POST請求,谷歌端點解決方案。以上答案很可能是正確的,但在Google Endpoint的情況下不起作用。
Google終端解決方案。
內容類型標頭必須設置爲「application/json」。
post("http://localhost:8888/_ah/api/langapi/v1/createLanguage",
"{\"language\":\"russian\", \"description\":\"dsfsdfsdfsdfsd\"}");
public static void post(String url, String param) throws Exception{
String charset = "UTF-8";
URLConnection connection = new URL(url).openConnection();
connection.setDoOutput(true); // Triggers POST.
connection.setRequestProperty("Accept-Charset", charset);
connection.setRequestProperty("Content-Type", "application/json;charset=" + charset);
try (OutputStream output = connection.getOutputStream()) {
output.write(param.getBytes(charset));
}
InputStream response = connection.getInputStream();
}
它肯定可以使用HttpClient來完成。
protected void sendJson(final String play, final String prop) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the childThread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 1000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost("http://192.168.0.44:80");
json.put("play", play);
json.put("Properties", prop);
StringEntity se = new StringEntity(json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if (response != null) {
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch (Exception e) {
e.printStackTrace();
showMessage("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
我建議http-request它基於Apache HTTP API。
HttpRequest<String> httpRequest = HttpRequestBuilder.createPost(yourUri, String.class)
.responseDeserializer(ResponseDeserializer.ignorableDeserializer()).build();
public void send(){
ResponseHandler<String> responseHandler = httpRequest.execute("details", yourJsonData);
int statusCode = responseHandler.getStatusCode();
String responseContent = responseHandler.orElse(null); // returns Content from response. If content isn't present returns null.
}
如果你想發送JSON
作爲請求體,您可以:
ResponseHandler<String> responseHandler = httpRequest.executeWithBody(yourJsonData);
我使用前higly建議更換閱讀文檔。
JSONObject j = new JSONObject(); j.put(「name」,「myname」); j.put(「age」,「20」); 那樣?我如何序列化它? – asdf007
@ asdf007只需使用'j.toString()'。 –
但這個連接不是異步....儀式? – gumuruh