- JSON字符串需要用urlencoding编码
- 对绝大多数HTTP client而言,URL长度都有上限,所以不能传太大的JSON,一般而言几K应该没问题,但是再长点就不好说了
- 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); // urlencoding编码
- //拼接路径字符串将参数包含进去
- 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;
- }
- }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)