通过httpclient向服务器传送数据并获得返回值

来源:互联网 发布:javascript map reduce 编辑:程序博客网 时间:2024/05/17 09:08

先上传主要代码

                                    Gson gson = new Gson();
JsonObject values2=new JsonObject();
   values2.addProperty("deviceId", "98:3b:34:df:2c:12");
String json = gson.toJson(values2);
String json64 = Base64.encodeToString(json.getBytes(), Base64.NO_WRAP);
ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
nvp.add(new BasicNameValuePair("type", "userinfo"));
nvp.add(new BasicNameValuePair("action", "001"));
nvp.add(new BasicNameValuePair("content", json64));
nvp.add(new BasicNameValuePair("contentkey", "#HQ*"));
   HttpClient httpClient = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), 6000000);
HttpConnectionParams.setSoTimeout(httpClient.getParams(), 120000);
HttpPost httpPost = new HttpPost(url);
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvp,HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
response = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {

e.printStackTrace();
} catch (IOException e) {

e.printStackTrace();
}

                           try {
String result=EntityUtils.toString(response.getEntity());
String[] split=result.split("#");
String s=split[2];
String s1=s.substring(0,s.length()-1);
String  resjson64 = new String(Base64.decode(s1, Base64.NO_WRAP));
System.out.println(resjson64+"**********");
try {
JSONObject jsonObj = new JSONObject(resjson64);
String uid=jsonObj.getString("ubid");
System.out.println(uid);
} catch (JSONException e) {
e.printStackTrace();
}
} catch (ParseException e) {

e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});

将要上传的数据封装成JSON格式,通过Base64把json数据编码,然后返回的信息通过Base64.decode(s1, Base64.NO_WRAP)解码,注意这里一定要通过String  resjson64 = new String(Base64.decode(s1, Base64.NO_WRAP));把解码的字符数组转换成String,否则得出的数据有误。

response.getEntity()在代码中只能出现一次,否则会报已使用异常。

0 4
原创粉丝点击