【发布时间】:2011-03-02 21:47:24
【问题描述】:
我想发送以下 JSON 文本
{"Email":"aaa@tbbb.com","Password":"123456"}
到网络服务并阅读响应。我知道如何阅读 JSON。问题是上面的 JSON 对象必须以变量名jason 发送。
我怎样才能从 android 做到这一点?创建请求对象、设置内容头等步骤有哪些?
【问题讨论】:
标签: android json post httprequest
我想发送以下 JSON 文本
{"Email":"aaa@tbbb.com","Password":"123456"}
到网络服务并阅读响应。我知道如何阅读 JSON。问题是上面的 JSON 对象必须以变量名jason 发送。
我怎样才能从 android 做到这一点?创建请求对象、设置内容头等步骤有哪些?
【问题讨论】:
标签: android json post httprequest
Android 没有专门的 HTTP 发送和接收代码,可以使用标准的 Java 代码。我建议使用 Android 附带的 Apache HTTP 客户端。这是我用来发送 HTTP POST 的 sn-p 代码。
我不明白在名为“jason”的变量中发送对象与任何事情有什么关系。如果您不确定服务器到底想要什么,请考虑编写一个测试程序来将各种字符串发送到服务器,直到您知道它需要采用什么格式。
int TIMEOUT_MILLISEC = 10000; // = 10 seconds
String postMessage="{}"; //HERE_YOUR_POST_STRING.
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient client = new DefaultHttpClient(httpParams);
HttpPost request = new HttpPost(serverUrl);
request.setEntity(new ByteArrayEntity(
postMessage.toString().getBytes("UTF8")));
HttpResponse response = client.execute(request);
【讨论】:
postMessage 未定义
如果您使用 Apache HTTP 客户端,从 Android 发送 json 对象很容易。这是有关如何执行此操作的代码示例。您应该为网络活动创建一个新线程,以免锁定 UI 线程。
protected void sendJson(final String email, final String pwd) {
Thread t = new Thread() {
public void run() {
Looper.prepare(); //For Preparing Message Pool for the child Thread
HttpClient client = new DefaultHttpClient();
HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); //Timeout Limit
HttpResponse response;
JSONObject json = new JSONObject();
try {
HttpPost post = new HttpPost(URL);
json.put("email", email);
json.put("password", pwd);
StringEntity se = new StringEntity( json.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
post.setEntity(se);
response = client.execute(post);
/*Checking response */
if(response!=null){
InputStream in = response.getEntity().getContent(); //Get the data in the entity
}
} catch(Exception e) {
e.printStackTrace();
createDialog("Error", "Cannot Estabilish Connection");
}
Looper.loop(); //Loop in the message queue
}
};
t.start();
}
您还可以使用Google Gson 发送和检索 JSON。
【讨论】:
public void postData(String url,JSONObject obj) {
// Create a new HttpClient and Post Header
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(myParams, 10000);
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpClient httpclient = new DefaultHttpClient(myParams );
String json=obj.toString();
try {
HttpPost httppost = new HttpPost(url.toString());
httppost.setHeader("Content-type", "application/json");
StringEntity se = new StringEntity(obj.toString());
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
HttpResponse response = httpclient.execute(httppost);
String temp = EntityUtils.toString(response.getEntity());
Log.i("tag", temp);
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
}
【讨论】:
以下链接提供了一个非常棒的 Android HTTP 库:
http://loopj.com/android-async-http/
简单的请求很容易:
AsyncHttpClient client = new AsyncHttpClient();
client.get("http://www.google.com", new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String response) {
System.out.println(response);
}
});
发送 JSON(感谢 https://github.com/loopj/android-async-http/issues/125 上的 `voidberg'):
// params is a JSONObject
StringEntity se = null;
try {
se = new StringEntity(params.toString());
} catch (UnsupportedEncodingException e) {
// handle exceptions properly!
}
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
client.post(null, "www.example.com/objects", se, "application/json", responseHandler);
这一切都是异步的,适用于 Android 并且可以安全地从您的 UI 线程调用。 responseHandler 将在您创建它的同一线程上运行(通常是您的 UI 线程)。它甚至有一个内置的 JSON 响应处理程序,但我更喜欢使用 google gson。
【讨论】:
HttpPost 已被 Android Api Level 22 弃用。因此,请使用HttpUrlConnection 进一步了解。
public static String makeRequest(String uri, String json) {
HttpURLConnection urlConnection;
String url;
String data = json;
String result = null;
try {
//Connect
urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
urlConnection.setDoOutput(true);
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestMethod("POST");
urlConnection.connect();
//Write
OutputStream outputStream = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
writer.write(data);
writer.close();
outputStream.close();
//Read
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
sb.append(line);
}
bufferedReader.close();
result = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
【讨论】:
现在由于HttpClient 已被弃用,当前的工作代码是使用HttpUrlConnection 创建连接并从连接中写入和读取。但我更喜欢使用Volley。这个库来自 android AOSP。我发现制作JsonObjectRequest 或JsonArrayRequest 非常容易使用
【讨论】:
没有什么比这更简单的了。使用 OkHttpLibrary
创建你的 json
JSONObject requestObject = new JSONObject();
requestObject.put("Email", email);
requestObject.put("Password", password);
然后像这样发送。
OkHttpClient client = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.addHeader("Content-Type","application/json")
.url(url)
.post(requestObject.toString())
.build();
okhttp3.Response response = client.newCall(request).execute();
【讨论】:
public class getUserProfile extends AsyncTask<Void, String, JSONArray> {
JSONArray array;
@Override
protected JSONArray doInBackground(Void... params) {
try {
commonurl cu = new commonurl();
String u = cu.geturl("tempshowusermain.php");
URL url =new URL(u);
// URL url = new URL("http://192.168.225.35/jabber/tempshowusermain.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type", "application/json");
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setDoOutput(true);
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setDoInput(true);
httpURLConnection.connect();
JSONObject jsonObject=new JSONObject();
jsonObject.put("lid",lid);
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
outputStream.write(jsonObject.toString().getBytes("UTF-8"));
int code = httpURLConnection.getResponseCode();
if (code == 200) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
}
object = new JSONObject(stringBuffer.toString());
// array = new JSONArray(stringBuffer.toString());
array = object.getJSONArray("response");
}
} catch (Exception e) {
e.printStackTrace();
}
return array;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected void onPostExecute(JSONArray array) {
super.onPostExecute(array);
try {
for (int x = 0; x < array.length(); x++) {
object = array.getJSONObject(x);
ComonUserView commUserView=new ComonUserView();// commonclass.setId(Integer.parseInt(jsonObject2.getString("pid").toString()));
//pidArray.add(jsonObject2.getString("pid").toString());
commUserView.setLid(object.get("lid").toString());
commUserView.setUname(object.get("uname").toString());
commUserView.setAboutme(object.get("aboutme").toString());
commUserView.setHeight(object.get("height").toString());
commUserView.setAge(object.get("age").toString());
commUserView.setWeight(object.get("weight").toString());
commUserView.setBodytype(object.get("bodytype").toString());
commUserView.setRelationshipstatus(object.get("relationshipstatus").toString());
commUserView.setImagepath(object.get("imagepath").toString());
commUserView.setDistance(object.get("distance").toString());
commUserView.setLookingfor(object.get("lookingfor").toString());
commUserView.setStatus(object.get("status").toString());
cm.add(commUserView);
}
custuserprof = new customadapterformainprofile(getActivity(),cm,Tab3.this);
gridusername.setAdapter(custuserprof);
// listusername.setAdapter(custuserprof);
} catch (Exception e) {
e.printStackTrace();
}
}
【讨论】: