1.使用HttpURLConnection
public static String getJsonByURL(String base_url) {
String url = base_url;
StringBuilder json = new StringBuilder();
String result = ""; try {
URL u = new URL(url);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
uc.setRequestMethod("GET");
//uc.setRequestMethod("POST");
/*
String cookieVal =uc.getHeaderField("Set-Cookie"); //获取session
String JSESSIONID = (cookieVal.substring(0,cookieVal.indexOf(";")));
uc.setRequestProperty("Cookie", JSESSIONID);//设置session
*/
BufferedReader bd = new BufferedReader(new InputStreamReader(uc.getInputStream(),"GBK"));
String s = null;
while((s=bd.readLine())!=null) {
json.append(s);
}
bd.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
result = json.toString(); return result;
}
2.使用HttpClient
(1)get
public static String getJsonByGet(String url) {
String s = "";
//CloseableHttpClient httpclient = HttpClients.createDefault();
DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
HttpGet httpget = new HttpGet(url);
CloseableHttpResponse response = null;
HttpEntity entity = null;
try {
response = httpclient.execute(httpget);
entity = response.getEntity();
/*
CookieStore cookieStore = httpclient.getCookieStore();//获取cookies
httpclient.setCookieStore(cookieStore);//设置cookies
*/
s = EntityUtils.toString(entity, "UTF-8");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
httpclient.close();
}
return s;
}
(POST)
public static String getJsonByPost(String url) { DefaultHttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
//CloseableHttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url); CloseableHttpResponse response = null;
HttpEntity entity = null;
String s = "";
try {
response = httpclient.execute(httppost);
entity = response.getEntity();
s = EntityUtils.toString(entity, "UTF-8");
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace(); }finally {
httpclient.close();
}
return s;
}
获取cookies和设置cookies的位置要根据不同的接口而定。
以上的方法是把接口的参数,在调用方法之前就配好了,作为url传入。也可在调用的相应方法内部做处理。
1.使用HttpURLConnection
public static byte[] getJsonByURL(String url, String params) throws Exception{
URL url = new URL(url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");//
// conn.setConnectTimeout(10000);//
// conn.setReadTimeout(2000);//
conn.setDoOutput(true);//
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream=conn.getInputStream();
return StreamTool.readInputStream(inStream);
}
对参数的处理有很多方法,可以append(),也可以自己+,不同参数,不同方法重载
2.使用HttpClient
package com.tradeyun; import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
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.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIUtils;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* @author QiaoJiafei
* @version 创建时间:2015年12月18日 上午10:03:12
* 类说明
*/
public class TestHttpClientParameter {
public static void main(String args[]) {
/* HttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
String s = "";
HttpResponse response = null;
HttpEntity entity = null;
String url = "http://172.16.30.244:8090/gm_product_site/assignmentApply/auth";
System.out.println("url=========="+url);
HttpPost post = new HttpPost(url);
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("applyId","1"));
formparams.add(new BasicNameValuePair("isPass","true"));
//formparams.add(new BasicNameValuePair("pwd","aaaaaa1"));
//formparams.add(new BasicNameValuePair("pwd", "aaaaaa1"));
UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); post.setEntity(uefEntity);
System.out.println("executing request " + post.getURI());
response = httpclient.execute(post);
entity = response.getEntity();
s= EntityUtils.toString(entity, "UTF-8");
System.out.println(s); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} */ //不成功
TestHttpClientParameter t = new TestHttpClientParameter();
t.post3();
} public void post3() {
HttpClient httpclient = new DefaultHttpClient(new PoolingClientConnectionManager());
String s = "";
HttpResponse response = null;
HttpEntity entity = null;
String url = "http://172.16.30.244:8090/gm_product_site/assignmentApply/auth";
System.out.println("url=========="+url);
HttpPost post = null;
List formparams = new ArrayList();
formparams.add(new BasicNameValuePair("applyId","1"));
formparams.add(new BasicNameValuePair("isPass","true")); UrlEncodedFormEntity uefEntity;
try {
uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8"); URI uri=null;
try {
uri = URIUtils.createURI("http", "172.16.30.244:8090", -1, "/gm_product_site/assignmentApply/auth",
URLEncodedUtils.format(formparams, "UTF-8"), null);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
post = new HttpPost(uri);
System.out.println(post.getURI());
response = httpclient.execute(post);
entity = response.getEntity();
s= EntityUtils.toString(entity, "UTF-8");
System.out.println(s); } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
httpclient也可以使用下面的方式:
package com.core.execute; import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils; /**
* @author QiaoJiafei
* @version 创建时间:2016年3月2日 上午10:54:24
* 类说明
*/
public class TestMapPara {
static HttpClient client = HttpClients.createDefault(); public static void main(String args[]) {
Map<String, String> map = new HashMap<String, String>();
map.put("id", "22");
postmap(map);
} private static void postmap(Map<String, String> params) {
// TODO Auto-generated method stub
String url = "http://172.16.30.73:8080/test/user/update";
HttpPost httppost = new HttpPost(url);
List<NameValuePair> ps = new ArrayList<NameValuePair>();
for (String pKey : params.keySet()) {
ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
}
try {
httppost.setEntity(new UrlEncodedFormEntity(ps));
//上面一行代码也可以使用带有编码格式的构造方法,如new UrlEncodedFormEntity(ps, "UTF-8");
HttpResponse response = client.execute(httppost);
HttpEntity httpEntity = response.getEntity();
System.out.println(EntityUtils.toString(httpEntity,"utf-8"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }