Java HttpClient Post多層json格式參數__大資料
來源:互聯網
上載者:User
package ...
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
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.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpWeiXinMessage {
public static String WeiXinMessage(String url,Map<String,String> params) throws ClientProtocolException, IOException{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.addHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");//要求標頭
/*方法一:一層json*/
//StringEntity stringEntity = new StringEntity(data,"UTF-8");
//httpPost.setEntity(stringEntity);//請求主體
/*方法二*:多層json*/
HttpWeiXinMessage.setPostData(httpPost, params);
HttpResponse httpResponse = httpClient.execute(httpPost);//發送請求
HttpEntity httpEntity = httpResponse.getEntity();//擷取請求返回體
String backResult = EntityUtils.toString(httpEntity,"UTF-8");//請求返回結果
if(httpResponse != null){
try{
EntityUtils.consume(httpResponse.getEntity());
}catch(IOException e){
e.printStackTrace();
}
}//釋放資源
return backResult;
}
//佈建要求參數
private static void setPostData(HttpPost httpPost, Map<String,String> params){
/*另外一種佈建要求參數方法*/
List<NameValuePair> list = new ArrayList<NameValuePair>();
for (Map.Entry<String, String> entry : params.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(),entry.getValue()));
}
HttpEntity httpEntity = null;
try {
httpEntity = new UrlEncodedFormEntity(list, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
httpPost.setEntity(httpEntity);//佈建要求主體
}
//傳遞Map<String,Strnig> params參數格式
Map<String, Strnig> map = new LinkedHashMap<String, String>();
map.put("contexcode", "log");
map.put("source", "weixin");
map.put("form", "WeChat");
map.put("messageId", "jjtz");
map.put("data", "{'touser':" + amv.getOpenId() + ",'data':{'first': {'value':'qjtz','color':'#0'}," +
"'keyword1':{'value':'"+realName+"','color':'#0'},'keyword2': {'value':'"+phone+"','color':'#173177'}," +
"'remark': {'value':'"+senderAddress+"','color':'#173177'}}}");
}