HttpClient4.5.3_Get_Post_请求

记一记:

package t.m1;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

/**
 * 粗粗过一下
 * @author Administrator
 *
 */
public class Test {

	public static void main(String[] args) throws Exception {

		get();
	}
	
	public static void get() throws Exception{
		
		HttpClient client = HttpClientBuilder.create().build();
		HttpGet httpGet = new HttpGet("http://www.sojson.com/open/api/weather/json.shtml?city=%E5%B9%BF%E5%B7%9E");
		// 设置连接超时
		final RequestConfig timeParams = RequestConfig.custom().setConnectTimeout(5000).build();
		httpGet.setConfig(timeParams);
		
		HttpResponse response = client.execute(httpGet);
	    int statusCode = response.getStatusLine().getStatusCode();
	    
	    System.out.println(statusCode);
	    System.out.println(statusCode == HttpStatus.SC_OK);

	    // 获取结果
	    BufferedReader br = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
	    StringBuffer result = new StringBuffer();
	    String content = null;
	    while ((content = br.readLine()) != null) {
	    	result.append(content);
	    }
	    br.close();
	    System.out.println(result.toString());
	}

	public static void post() throws Exception{

		HttpClient client = HttpClientBuilder.create().build();
		HttpPost post = new HttpPost("http://127.0.0.1:8099/xxx/mobile/t/t1.do");
		
		// 请求参数
		List<NameValuePair> params = new ArrayList<NameValuePair>();
	    params.add(new BasicNameValuePair("k", "abc"));
	    post.setEntity(new UrlEncodedFormEntity(params));
	    
	    // 设置连接超时
	    final RequestConfig timeParams = RequestConfig.custom().setConnectTimeout(5000).build();
	    post.setConfig(timeParams);
	    
		HttpResponse response = client.execute(post);
	    int statusCode = response.getStatusLine().getStatusCode();
	    System.out.println(statusCode);
	    System.out.println(statusCode == HttpStatus.SC_OK);

	    // 获取结果
	    BufferedReader br = new BufferedReader( new InputStreamReader(response.getEntity().getContent()));
	    StringBuffer result = new StringBuffer();
	    String content = null;
	    while ((content = br.readLine()) != null) {
	    	result.append(content);
	    }
	    br.close();
	    System.out.println(result.toString());
	}
}

OK

猜你喜欢

转载自blog.csdn.net/u013845177/article/details/79030596