用HttpClient中的GetMethod和PostMethod的接口访问

GetMethod

  1. 简单的一个Test
package com.etc.task;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.net.URLEncoder;

public class Test {
    public static void getG(){
        //1.创建 HttpClient
        HttpClient client = new HttpClient();
        String s = null;
        try {
            //中文转码
            s = URLEncoder.encode("A有限公司", "UTF-8");
            //2.构造GetMethod的实例
            GetMethod getMethod = new GetMethod("http://192.xxx.xxx.xx:8088/GetBlist.query_blist_info?customer_name="+s);
            
            getMethod.addRequestHeader("Content-Type", "text/html; charset=UTF-8");
            int i = client.executeMethod(getMethod);
            
            //getMethod.getResponseBodyAsString()获取返回的json
            System.out.println(i+","+getMethod.getResponseBodyAsString());
            
            JSONObject jsonObject = JSONObject.fromObject(getMethod.getResponseBodyAsString());
            String data = jsonObject.getString("data");
            JSONObject jsonData = JSONObject.fromObject(data.substring(1,data.length()-1));
            String cstFlag = jsonData.getString("cst_flag");
            System.out.println("cst_flag="+cstFlag);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        getG();
    }
}

得到
在这里插入图片描述

PostMethod

  1. 一个简单的Test例子
package com.etc.task;

import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;
import java.net.URLEncoder;

public class Test {
    public static void getP(){
    
    	//1.创建 HttpClient
        HttpClient client = new HttpClient();
        
        String url = "192.168.xxx.xx:8080/xxx"
        //2.构造PostMethod 的实例
        PostMethod postMethod = new PostMethod(url);
        
        postMethod.addRequestHeader("Content-Type", "application/x-www-urlencoded; charset=UTF-8");
        
        //3.请求参数,方式一(简单)
        postMethod.addParameter("customer_name","xxxxx");
        /*
        //请求参数方式二
        NameValuePair[] data = {
                new NameValuePair("customer_name","xxxx"),
                new NameValuePair("customer_name2","yyy")
        };
        postMethod.setRequestBody(data);
        */
        
        try {
            int i = client.executeMethod(postMethod);
            System.out.println(i+","+postMethod.getResponseBodyAsString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args){
        getP();
    }
}

你可能感兴趣的:(用HttpClient中的GetMethod和PostMethod的接口访问)