Java 通过别人提供的http接口获取信息
package com.web.util;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
public class HttpRequestUtil {
public static String addUrl(String head, String tail) {
if (head.endsWith("/")) {
if (tail.startsWith("/")) {
return head.substring(0, head.length() - 1) + tail;
} else {
return head + tail;
}
} else {
if (tail.startsWith("/")) {
return head + tail;
} else {
return head + "/" + tail;
}
}
}
public synchronized static String postData(String url, Map<String, String> params, String codePage) throws Exception {
final HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);
final PostMethod method = new PostMethod(url);
if (params != null) {
method.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, codePage);
method.setRequestBody(assembleRequestParams(params));
}
String result = "";
try {
httpClient.executeMethod(method);
result = new String(method.getResponseBody(), codePage);
} catch (final Exception e) {
throw e;
} finally {
method.releaseConnection();
}
return result;
}
public synchronized static String postData(String url, String codePage) throws Exception {
final HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10 * 1000);
httpClient.getHttpConnectionManager().getParams().setSoTimeout(10 * 1000);
final GetMethod method = new GetMethod(url);
String result = "";
try {
httpClient.executeMethod(method);
result = new String(method.getResponseBody(), codePage);
} catch (final Exception e) {
throw e;
} finally {
method.releaseConnection();
}
return result;
}
/**
* 组装http请求参数
*
* @param params
* @param menthod
* @return
*/
private synchronized static NameValuePair[] assembleRequestParams(Map<String, String> data) {
final List<NameValuePair> nameValueList = new ArrayList<NameValuePair>();
Iterator<Map.Entry<String, String>> it = data.entrySet().iterator();
while (it.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) it.next();
nameValueList.add(new NameValuePair((String) entry.getKey(), (String) entry.getValue()));
}
return nameValueList.toArray(new NameValuePair[nameValueList.size()]);
}
}
1.引入相应的jar包(.net)
2.创建连接
3.发送post请求
4.读取响应
5.断开链接
注意:
传参:1.可以在链接后边加参数(不推荐)
2.一般都是把参数封装成一个json字符串,然后发送过去。out.writeBytes(jsonStr);
例子:
String urlStr = "http://my.b2b.hc360.com/my/turbine/template/firstview,corinfo4chat.html?username=jinjiangjiayi";
// String str = new PostHttpClient().postHttp(url1, tradeId);
StringBuffer strBuf = new StringBuffer("");
try {
//创建连接
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
// out.writeBytes(jsonStr);
out.flush();
out.close();
//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
strBuf.append(lines);
}
//返回的请求信息
System.out.println(strBuf);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("++++++++++++++++++++++++");
System.out.println(strBuf);
例子:
package cn.com.speed.busdevelop.util;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.struts2.ServletActionContext;
import cn.com.speed.busdevelop.action.account.AccountAction;
import cn.com.speed.busdevelop.po.Account;
import cn.com.speed.busdevelop.service.AccountService;
import cn.com.speed.busdevelop.service.impl.AccountServiceImpl;
import com.sdicons.json.mapper.JSONMapper;
import com.sdicons.json.mapper.MapperException;
public static void main(String[] args) {
// String urlStr1 = "http://localhost:8080/devp1/account/accountAction!queryListAccount.action?cid=POS101&cmd=201&version=1.0&returnType=json&userId=liangzg&verify=";
// new PostHttpClient().postHttp(urlStr1, "");
// String tradeId = "140521181509XX030056";
String urlStr = "http://192.168.12.13:8080/devp1/account/account!queryListAccount.action?cmd=201&verify=813828425fe78f57cb46acddf1edd9e4&userId=houlj1&cid=POS101&returnType=json&version=1.0";
// String str = new PostHttpClient().postHttp(url1, tradeId);
// System.out.println(str);
System.out.println("--------------------------------------------");
Map map = new HashMap();
map.put("cid", "POS101");//系统标识
map.put("cmd", "201");//命令字
map.put("version", "1.0");//接口版本
map.put("returnType", "json");//报文格式
String md5String = MD5.getSign(map, "123456789", "MD5", "UTF-8");
map.put("userId", "liangzg");
// map.put("sign", MD5.getSign(map,"123456789", "MD5", "UTF-8"));
// String urlStr = "http://localhost:8080/devp1/account/accountAction!queryListAccount.action?cid=POS101&cmd=201&version=1.0&returnType=json&userId=liangzg&verify="+md5String;
String jsonStr = null;
try {
jsonStr = JSONMapper.toJSON(map).render(false);
} catch (MapperException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// System.out.println(jsonStr);
StringBuffer strBuf = new StringBuffer("");
try {
//创建连接
URL url = new URL(urlStr);
HttpURLConnection connection = (HttpURLConnection) url
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.connect();
//POST请求
DataOutputStream out = new DataOutputStream(
connection.getOutputStream());
out.writeBytes(jsonStr);
out.flush();
out.close();
//读取响应
BufferedReader reader = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String lines;
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
strBuf.append(lines);
}
//返回的请求信息
// System.out.println(strBuf);
reader.close();
// 断开连接
connection.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("++++++++++++++++++++++++");
System.out.println(strBuf);
}
}
浙公网安备 33010602011771号