Java程序中请求http接口

Java请求http接口

方法1
此方法需要httpclient-4.4.jar,httpcore-4.4.jar,并在头部引入包

import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
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.HttpClients;

程序实现:

	String resulturl = "http://localhost:9080/projectName/servletName";  //请求的http接口
	HttpPost httppost = new HttpPost(resulturl);
	
	String param="taskid="+taskid;	//请求的发送的参数,如果请求没有参数可以不写。也可以直接在请求字符串中以'?'拼接参数
	System.out.println(resulturl+"?"+param);		
	StringEntity s=new StringEntity(param);
	s.setContentType("application/x-www-form-urlencoded");
	httppost.setEntity(s);
	
	HttpClient httpclient = HttpClients.custom().build(); //定义一个http客户端请求
	HttpResponse result= httpclient.execute(httppost);  //执行http请求
	StatusLine statusline = result.getStatusLine(); //获取请求的返回内容
    System.out.println(statusline);

方法2
使用Java的URL类中的方法

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

	try {
		URL url = new URL("http://83.10.61.5:8080/AndroidAgent/adbdevices");
		InputStream is = url.openStream();
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		String line = null;
		while((line = br.readLine()) != null) {
			System.out.println(line);;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}

你可能感兴趣的:(JAVA)