您的位置:首页 > 理论基础 > 计算机网络

java HttpClient get post请求 调用接口

2014-07-13 14:16 886 查看
使用HttpClient前需要准备第三方jar包及依赖包,这里提供百度云盘的下载地址:
http://yunpan.cn/Qhh5CipmriaUh(提取码:6220)
package com.main;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;

@SuppressWarnings("deprecation")
public class doMain {

public static void main(String[] args) throws IllegalStateException, IOException {
doPost();
}

@SuppressWarnings({ "unused", "resource" })
public static void doPost() throws IllegalStateException, IOException {
// ====================POST方式调用======================================
String result = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost("http://192.168.1.69:8080/Text/login");//目标地址

// 设置值: username=admin&password=1234567
List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
//这里使用map来存储请求的数据,因为fastjson可以使对象转换为json字符串
Map<String, String> map = new HashMap<String, String>();
map.put("username", "admin");
map.put("userpwd", "1234567");

//params的值就是对应用户名和密码,也就是map,而在服务端则需要根据params来获取值
postParameters.add(new BasicNameValuePair("params", JSON.toJSONString(map)));
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, "utf-8");
httpPost.setEntity(formEntity);
HttpResponse response = httpclient.execute(httpPost);//执行请求

if (response.getStatusLine().getStatusCode() == 200) {//如果返回200状态代表成功
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
String str = convertStreamToString(instreams);//服务端返回字符流,值需要解析它就获取字符串
System.out.println(str);//如果返回的字符串是json格式的,就需要用解析json的方法解析
// 解析json
// JSONObject js = JSON.parseObject(str);
// JSONArray jsonarray = js.getJSONArray("name");
// for (int i = 0; i < jsonarray.size(); i++) {
// String a = (String) jsonarray.get(i);
// System.out.print("名字" + (i + 1) + ":" + a + " ");
// }
// System.out.println("");
// System.out.println("年龄:" + js.getString("age"));
// System.out.println("性别:" + js.getString("sex"));
httpPost.abort();
}
}
}

public static void doGet() throws IllegalStateException, IOException {
// ====================GET方式调用======================================
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpgets = new HttpGet("http://192.168.1.69:8080/Text/getuser");
HttpResponse response = httpclient.execute(httpgets);
if (response.getStatusLine().getStatusCode() == 200) {
HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream instreams = entity.getContent();
String str = convertStreamToString(instreams);
System.out.println(str);

JSONObject js = JSON.parseObject(str);
JSONArray jsonarray = js.getJSONArray("name");
for (int i = 0; i < jsonarray.size(); i++) {
String a = (String) jsonarray.get(i);
System.out.print("名字" + (i + 1) + ":" + a + " ");
}
System.out.println("");
System.out.println("年龄:" + js.getString("age"));
System.out.println("性别:" + js.getString("sex"));
httpgets.abort();
}
}
}

/**
* 流文件转换成String
*
* @param inputStream
* @return String
*/
public static String convertStreamToString(InputStream inputStream) {
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

@SuppressWarnings("unused")
private static String ConvertStream2Json(InputStream inputStream) {
String jsonStr = "";
// ByteArrayOutputStream相当于内存输出流
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
// 将输入流转移到内存输出流中
try {
while ((len = inputStream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
// 将内存流转换为字符串
jsonStr = new String(out.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return jsonStr;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: