加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

《Java知识应用》Java通过Get和Post实现HTTP请求。

发布时间:2020-12-15 07:31:39 所属栏目:Java 来源:网络整理
导读:Http请求,是非常常见并且的数据交互方式。 下面讲解:Get和Post的两个实战案例。 ? 用于测试的Action(controller)。 @RequestMapping(value = "getData.json" ) public @ResponseBodyServerResponse getData(HttpSession session,@RequestBody People peo

Http请求,是非常常见并且的数据交互方式。

下面讲解:Get和Post的两个实战案例。

?

用于测试的Action(controller)。

@RequestMapping(value = "getData.json")
public @ResponseBody
ServerResponse getData(HttpSession session,@RequestBody People people){
    return new ServerResponse(people);
}

?

案例(post):

import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

public class Main {
    private static final String URL= "http://XXX.XXX.XXX.XXX:XXXX/getData.json";

    public static void main(String[] args) {
        String url = URL;
        Map map = new HashMap();
        map.put("name","李磊");
        map.put("age","18");
        JSONObject json = new JSONObject(map);
        JSONObject res = PostInterface.postJson(url,json);
        System.out.println(res.toString());
    }
}
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import java.nio.charset.Charset;

/**
 * 请求类
 */
public class PostInterface {

    public static JSONObject postJson(String url,JSONObject json) {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpPost post = new HttpPost(url);
        JSONObject response = null;
        try {
            //编码使用UTF-8,避免中文乱码
            StringEntity s = new StringEntity(json.toString(),Charset.forName("GBK"));
            s.setContentType("application/json");//发送json数据需要设置contentType
            post.setEntity(s);

            HttpResponse res = httpclient.execute(post);
            if(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                String result = EntityUtils.toString(res.getEntity());// 返回json格式:
                response = new JSONObject(result);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return response;
    }
}

运行结果:

?

用于测试的Action(controller)。

@RequestMapping(value = "getData.json")
public @ResponseBody
ServerResponse getData(HttpSession session,String flag){
    String str;
    if(!StringUtils.isBlank(flag)){
        str = "您传的是“"+flag+"”";
    }else{
        str = "您传的是空";
    }
    return new ServerResponse(str);
}

?

案例(get):

public class Main {
    private static final String URL= "http://XXX.XXX.XXX.XXX:XXXX/getData.json";

    public static void main(String[] args) {
        String url = URL;
        String res = PostInterface.doGet(url+"?flag=1","utf-8");
        System.out.println(res.toString());
    }
}
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

/**
 * 请求类
 */
public class PostInterface {

    public static String doGet(String url,String charset){
        if(null == charset){
            charset = "utf-8";
        }
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        HttpGet httpGet = null;
        String result = null;
        try {
            httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            if(response != null){
                HttpEntity resEntity = response.getEntity();
                if(resEntity != null){
                    result = EntityUtils.toString(resEntity,charset);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}

运行结果:

?

如果在执行案例过程遇到问题:可以加群沟通,或者下面留言

?

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读