Java 通过HttpClient Post方式提交json,并从服务端返回json数据

直接上代码吧,和前面几篇文章都差不多

java代码:

package PostPager;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class PostXml {



    public static void main(String args[]) {
        try {
            JSONObject  obj = new JSONObject();
                obj.append("app_name", "全民大讨论");
                obj.append("app_ip", "10.21.243.234");
                obj.append("app_port", 8080);
                obj.append("app_type", "001");
                obj.append("app_area", "asd");

            CloseableHttpClient httpclient = HttpClients.createDefault();
            System.out.println(obj);

            HttpPost httpPost = new HttpPost("http://119.29.85.118//test.php");
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");

            // 解决中文乱码问题
            StringEntity stringEntity = new StringEntity(obj.toString(), "UTF-8");
            stringEntity.setContentEncoding("UTF-8");

            httpPost.setEntity(stringEntity);

            // CloseableHttpResponse response =
            // httpclient.execute(httpPost);

            System.out.println("Executing request " + httpPost.getRequestLine());

            // Create a custom response handler
            ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
                @Override
                public String handleResponse(final HttpResponse response)
                        throws ClientProtocolException, IOException {//
                    int status = response.getStatusLine().getStatusCode();
                    if (status >= 200 && status < 300) {

                        HttpEntity entity = response.getEntity();

                        return entity != null ? EntityUtils.toString(entity) : null;
                    } else {
                        throw new ClientProtocolException(
                                "Unexpected response status: " + status);
                    }
                }
            };
            String responseBody = httpclient.execute(httpPost, responseHandler);
            System.out.println("----------------------------------------");
            System.out.println(responseBody);

        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

服务端test.php代码:

 <?php
         $result = file_get_contents('php://input');
         echo $result;
         echo json_decode(json_encode($result));

 ?>

输出结果:
{“app_name”:[“全民大讨论”],”app_ip”:[“10.21.243.234”],”app_type”:[“001”],”app_port”:[8080],”app_area”:[“asd”]}

Executing request POST http://119.29.85.118//test.php HTTP/1.1

{“app_name”:[“全民大讨论”],”app_ip”:[“10.21.243.234”],”app_type”:[“001”],”app_port”:[8080],”app_area”:[“asd”]}{“app_name”:[“全民大讨论”],”app_ip”:[“10.21.243.234”],”app_type”:[“001”],”app_port”:[8080],”app_area”:[“asd”]}

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java后端可以使用HttpClient库来实现Post提交文件流及参数的功能。示例代码如下: ```java CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); // 添加文件流 builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, fileName); // 添加参数 builder.addTextBody("param1", "value1", ContentType.TEXT_PLAIN); builder.addTextBody("param2", "value2", ContentType.TEXT_PLAIN); HttpEntity multipart = builder.build(); httpPost.setEntity(multipart); CloseableHttpResponse response = httpClient.execute(httpPost); ``` 其中,`url`是要提交到的服务端地址,`file`是要提交的文件流,`fileName`是文件名。`param1`和`param2`是要提交的参数及其对应的值。 在服务端接收文件流及参数时,可以使用Spring框架的`MultipartFile`来接收文件流,使用`@RequestParam`来接收参数。示例代码如下: ```java @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("param1") String param1, @RequestParam("param2") String param2) throws IOException { byte[] bytes = file.getBytes(); // 处理文件流和参数 return "success"; } ``` 其中,`/upload`是服务端接收请求的地址,`file`是要接收的文件流,`param1`和`param2`是要接收的参数。 注意,在服务端接收参数时,需要根据参数的类型来设置参数的`ContentType`。例如,如果参数是文本类型,则设置为`ContentType.TEXT_PLAIN`。如果参数是JSON类型,则设置为`ContentType.APPLICATION_JSON`。 以上就是Java后端HttpClient Post提交文件流及参数的实现方式

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值