111 post android json httprequest
我试图弄清楚如何使用HTTPClient从Android发布JSON.我一直试图解决这个问题,我已经在网上找到了很多例子,但我无法让它们中的任何一个工作.我相信这是因为我缺乏一般的JSON /网络知识.我知道那里有很多例子,但有人可以指点我一个实际的教程吗?我正在寻找一步一步的过程,包括代码和解释为什么你要做每一步,或者说那个步骤做了什么.它不需要是复杂的,简单的就足够了.
再一次,我知道那里有很多例子,我只是在寻找一个例子来解释究竟发生了什么以及为什么这样做.
如果有人知道关于这个的好Android手册,请告诉我.
再次感谢@terrance的帮助,这是我在下面描述的代码
public void shNameVerParams() throws Exception{
String path = //removed
HashMap params = new HashMap();
params.put(new String("Name"), "Value");
params.put(new String("Name"), "Value");
try {
HttpClient.SendHttpPost(path, params);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
Ter*_*nce 157
在这个答案中,我使用的是Justin Grammens发布的一个例子.
JSON代表JavaScript Object Notation.在JavaScript中,可以像这样引用属性object1.name
,就像这样 object['name'];
.本文中的示例使用了这一点JSON.
部件
一个粉丝对象,电子邮件为密钥,foo @ bar.com为值
{
fan:
{
email : 'foo@bar.com'
}
}
Run Code Online (Sandbox Code Playgroud)
所以等价的对象是fan.email;
或fan['email'];
.两者都具有相同的值'foo@bar.com'
.
以下是我们的作者用于制作HttpClient请求的内容.我并不认为自己是这方面的专家,所以如果有人有更好的方式来解释一些术语,那就免费了.
public static HttpResponse makeRequest(String path, Map params) throws Exception
{
//instantiates httpclient to make request
DefaultHttpClient httpclient = new DefaultHttpClient();
//url with the post data
HttpPost httpost = new HttpPost(path);
//convert parameters into JSON object
JSONObject holder = getJsonObjectFromMap(params);
//passes the results to a string builder/entity
StringEntity se = new StringEntity(holder.toString());
//sets the post request as the resulting string
httpost.setEntity(se);
//sets a request header so the page receving the request
//will know what to do with it
httpost.setHeader("Accept", "application/json");
httpost.setHeader("Content-type", "application/json");
//Handles what is returned from the page
ResponseHandler responseHandler = new BasicResponseHandler();
return httpclient.execute(httpost, responseHandler);
}
Run Code Online (Sandbox Code Playgroud)
如果您不熟悉Map
数据结构,请查看Java Map参考.简而言之,地图类似于字典或散列.
private static JSONObject getJsonObjectFromMap(Map params) throws JSONException {
//all the passed parameters from the post request
//iterator used to loop through all the parameters
//passed in the post request
Iterator iter = params.entrySet().iterator();
//Stores JSON
JSONObject holder = new JSONObject();
//using the earlier example your first entry would get email
//and the inner while would get the value which would be 'foo@bar.com'
//{ fan: { email : 'foo@bar.com' } }
//While there is another entry
while (iter.hasNext())
{
//gets an entry in the params
Map.Entry pairs = (Map.Entry)iter.next();
//creates a key for Map
String key = (String)pairs.getKey();
//Create a new map
Map m = (Map)pairs.getValue();
//object for storing Json
JSONObject data = new JSONObject();
//gets the value
Iterator iter2 = m.entrySet().iterator();
while (iter2.hasNext())
{
Map.Entry pairs2 = (Map.Entry)iter2.next();
data.put((String)pairs2.getKey(), (String)pairs2.getValue());
}
//puts email and 'foo@bar.com' together in map
holder.put(key, data);
}
return holder;
}
Run Code Online (Sandbox Code Playgroud)
请随时评论有关这篇文章的任何问题,或者如果我没有做出明确的事情,或者我没有触及你仍然感到困惑的事情......等等.
(如果Justin Grammens不同意,我会退出.但如果没有,那么感谢Justin对此感到很酷.)
我刚刚发表了关于如何使用代码的评论,并意识到返回类型中存在错误.方法签名设置为返回一个字符串,但在这种情况下它没有返回任何东西.我将签名更改为HttpResponse并将引用此链接获取响应主体的HttpResponse 路径变量是url并更新以修复代码中的错误.
JJD*_*JJD 41
这是@Ttrance答案的另一种解决方案.您可以轻松地外包转换.该GSON图书馆做一朵奇葩把各种数据结构到JSON和周围的其他方式.
public static void execute() {
Map<String, String> comment = new HashMap<String, String>();
comment.put("subject", "Using the GSON library");
comment.put("message", "Using libraries is convenient.");
String json = new GsonBuilder().create().toJson(comment, Map.class);
makeRequest("http://192.168.0.1:3000/post/77/comments", json);
}
public static HttpResponse makeRequest(String uri, String json) {
try {
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(json));
httpPost.setHeader("Accept", "application/json");
httpPost.setHeader("Content-type", "application/json");
return new DefaultHttpClient().execute(httpPost);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Run Code Online (Sandbox Code Playgroud)
类似的可以通过使用杰克逊而不是Gson 来完成.我还建议你看看Retrofit,它为你隐藏了很多样板代码.对于更有经验的开发人员,我建议您尝试使用RxAndroid.
Egi*_*gis 33
我建议使用这个HttpURLConnection
代替HttpGet
.正如HttpGet
Android API级别22中已弃用的那样.
HttpURLConnection httpcon;
String url = null;
String data = null;
String result = null;
try {
//Connect
httpcon = (HttpURLConnection) ((new URL (url).openConnection()));
httpcon.setDoOutput(true);
httpcon.setRequestProperty("Content-Type", "application/json");
httpcon.setRequestProperty("Accept", "application/json");
httpcon.setRequestMethod("POST");
httpcon.connect();
//Write
OutputStream os = httpcon.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(data);
writer.close();
os.close();
//Read
BufferedReader br = new BufferedReader(new InputStreamReader(httpcon.getInputStream(),"UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Run Code Online (Sandbox Code Playgroud)
此任务的代码太多,请检查此库https://github.com/kodart/Httpzoid 内部使用GSON并提供适用于对象的API.隐藏所有JSON详细信息.
Http http = HttpFactory.create(context);
http.get("http://example.com/users")
.handler(new ResponseHandler<User[]>() {
@Override
public void success(User[] users, HttpResponse response) {
}
}).execute();
Run Code Online (Sandbox Code Playgroud)