mom*_*omo 159
这是你需要做的:
代码大致看起来像(你仍然需要调试它并让它工作)
//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();
}
Run Code Online (Sandbox Code Playgroud)
Pra*_*ash 89
您可以使用Gson库将您的Java类转换为JSON对象.
按照上面的示例为要发送的变量创建一个pojo类
{"name":"myname","age":"20"}
Run Code Online (Sandbox Code Playgroud)
变
class pojo1
{
String name;
String age;
//generate setter and getters
}
Run Code Online (Sandbox Code Playgroud)
一旦你在pojo1类中设置变量,你可以使用以下代码发送它
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);
Run Code Online (Sandbox Code Playgroud)
这些是进口
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;
Run Code Online (Sandbox Code Playgroud)
而对于GSON
import com.google.gson.Gson;
Run Code Online (Sandbox Code Playgroud)
Leo*_*lva 43
@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();
}
Run Code Online (Sandbox Code Playgroud)
Ale*_*ill 20
使用HttpURLConnection可能最简单.
http://www.xyzws.com/Javafaq/how-to-use-httpurlconnection-post-data-to-web-server/139
您将使用JSONObject或其他任何内容构建您的JSON,但不能处理网络; 你需要序列化它,然后将它传递给HttpURLConnection进行POST.
小智 14
试试这段代码:
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();
}
Run Code Online (Sandbox Code Playgroud)
Med*_*edo 14
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();
}
Run Code Online (Sandbox Code Playgroud)
yur*_*rin 10
我发现这个问题正在寻找有关如何从Java客户端向Google端点发送帖子请求的解决方案.以上答案,很可能是正确的,但在Google端点的情况下无效.
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();
}
Run Code Online (Sandbox Code Playgroud)
确定也可以使用HttpClient来完成.
您可以将以下代码用于Apache HTTP:
String payload = "{\"name\": \"myname\", \"age\": \"20\"}";
post.setEntity(new StringEntity(payload, ContentType.APPLICATION_JSON));
response = client.execute(request);
Run Code Online (Sandbox Code Playgroud)
另外,您可以创建一个json对象,并像这样将字段放入对象
HttpPost post = new HttpPost(URL);
JSONObject payload = new JSONObject();
payload.put("name", "myName");
payload.put("age", "20");
post.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
Run Code Online (Sandbox Code Playgroud)
小智 6
对于 Java 11,您可以使用新的HTTP 客户端:
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost/api"))
.header("Content-Type", "application/json")
.POST(ofInputStream(() -> getClass().getResourceAsStream(
"/some-data.json")))
.build();
client.sendAsync(request, BodyHandlers.ofString())
.thenApply(HttpResponse::body)
.thenAccept(System.out::println)
.join();
Run Code Online (Sandbox Code Playgroud)
您可以使用来自InputStream、String、 的发布者File。可以使用 Jackson将 JSON 转换为 aString或IS。
| 归档时间: |
|
| 查看次数: |
637058 次 |
| 最近记录: |