项目中与对方进行数据交互时,对方提供了一套夸域json方式传递数据,并给出了一个js示例
-
$.getJSON(
-
“http://www.—-aspx?callback=?”
,
-
{Name:
“123”
,Pass:
“123”
},
-
function
(json){
-
if
(json.UserId==
null
){
-
alert(
“NO”
);
-
}
else
{
-
alert(json.UserId);
-
}
-
}
-
);
但是此方法处理数据时,只能在页面中进行,局限性很大。因此在具体实施时,使用了HttpClient来代替。
-
import
java.io.InputStreamReader;
-
import
java.util.ArrayList;
-
import
java.util.List;
-
-
import
org.apache.http.HttpEntity;
-
import
org.apache.http.HttpResponse;
-
import
org.apache.http.HttpStatus;
-
import
org.apache.http.NameValuePair;
-
import
org.apache.http.client.HttpClient;
-
import
org.apache.http.client.methods.HttpGet;
-
import
org.apache.http.client.utils.URLEncodedUtils;
-
import
org.apache.http.impl.client.DefaultHttpClient;
-
import
org.apache.http.message.BasicNameValuePair;
-
import
org.apache.http.protocol.HTTP;
-
import
org.json.JSONException;
-
import
org.json.JSONObject;
-
import
org.json.JSONTokener;
-
-
-
/**
-
* 使用HttpClient请求页面并返回json格式数据.
-
* 对方接收的也是json格式数据。
-
* 因此使用HttpGet。
-
* */
-
public
class
Json {
-
-
public
static
void
main(String[] args)
throws
JSONException {
-
-
JSONObject json =
new
JSONObject();
-
List<NameValuePair> params =
new
ArrayList<NameValuePair>();
-
params.add(
new
BasicNameValuePair(
“Name”
,
“123”
));
-
params.add(
new
BasicNameValuePair(
“Pass”
,
“123”
));
-
//要传递的参数.
-
String url =
“http://www.—-aspx?”
+ URLEncodedUtils.format(params, HTTP.UTF_8);
-
//拼接路径字符串将参数包含进去
-
json = get(url);
-
System.out.println(json.get(
“UserId”
));
-
-
}
-
-
public
static
JSONObject get(String url) {
-
-
HttpClient client =
new
DefaultHttpClient();
-
HttpGet get =
new
HttpGet(url);
-
JSONObject json =
null
;
-
try
{
-
HttpResponse res = client.execute(get);
-
if
(res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
-
HttpEntity entity = res.getEntity();
-
json =
new
JSONObject(
new
JSONTokener(
new
InputStreamReader(entity.getContent(), HTTP.UTF_8)));
-
}
-
}
catch
(Exception e) {
-
throw
new
RuntimeException(e);
-
-
}
finally
{
-
//关闭连接 ,释放资源
-
client.getConnectionManager().shutdown();
-
}
-
return
json;
-
}
-
}