如何使用 Android 通过 Request 发送 JSON 对象?
Posted
技术标签:
【中文标题】如何使用 Android 通过 Request 发送 JSON 对象?【英文标题】:How to send a JSON object over Request with Android? 【发布时间】:2011-03-02 21:47:24 【问题描述】:我想发送以下 JSON 文本
"Email":"aaa@tbbb.com","Password":"123456"
到网络服务并阅读响应。我知道如何阅读 JSON。问题是上面的 JSON 对象必须以变量名jason
发送。
我怎样才能从 android 做到这一点?创建请求对象、设置内容头等步骤是什么
【问题讨论】:
【参考方案1】: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();
【讨论】:
【参考方案2】: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 是 JSON 对象吗?postMessage
未定义
超时时间是多少?
如果传递多个字符串怎么办?像 postMessage2.toString().getBytes("UTF8")
建议将 POJO 转换为 Json 字符串?【参考方案3】:
没有什么比这更简单的了。使用 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();
【讨论】:
赞成指向 okhttp,这是一个有用的库,但给出的代码并没有多大帮助。例如,传递给 RequestBody.create() 的参数是什么?有关详细信息,请参阅此链接:vogella.com/tutorials/JavaLibrary-OkHttp/article.html【参考方案4】:现在由于HttpClient
已被弃用,当前的工作代码是使用HttpUrlConnection
创建连接并从连接中写入和读取。但我更喜欢使用Volley。这个库来自 android AOSP。我发现制作JsonObjectRequest
或JsonArrayRequest
非常容易使用
【讨论】:
【参考方案5】: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;
【讨论】:
接受的答案已贬值,这种方法更好【参考方案6】: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)
【讨论】:
我已将 json 对象发布到 ASP.Net mvc 服务器。如何在 ASP.Net 服务器中查询相同的 json 字符串?【参考方案7】:以下链接提供了一个非常棒的 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 的 resonseHandler,但我更喜欢使用 google gson。
【讨论】:
你知道这个运行的最小 sdk 吗? 如果它有最小值,我会感到惊讶,因为它不是 GUI。为什么不尝试一下并发布您的发现。 好吧,我决定改用原生库。有更多关于这方面的信息,因为我对 android 相当陌生。我真的是一个 ios 开发者。它更好,因为我阅读了所有文档,而不是仅仅插入和使用其他人的代码。不过谢谢【参考方案8】:如果您使用 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。
【讨论】:
您好,服务器是否可能要求我设置一个名为 JSON 的标头并将 json 内容放入该标头中?我将 url 发送为 HttpPost post=new HttpPost("abc.com/xyz/usersgetuserdetails"); 但它说无效请求错误。代码的remiander是相同的。其次json = header = new JSONObject(); 这是发生了什么跨度> 我不确定服务器期望什么样的请求。至于这个 ' json = header = new JSONObject(); ' 它只是创建了 2 个 json 对象。 @primpop - 您是否有机会提供一个简单的 php 脚本来配合这个?我尝试实现您的代码,但我一生无法让它发送除 NULL 以外的任何内容。 你可以像这样 StringWriter writer = new StringWriter(); IOUtils.copy(in, writer, "UTF-8"); String theString = writer.toString();以上是关于如何使用 Android 通过 Request 发送 JSON 对象?的主要内容,如果未能解决你的问题,请参考以下文章
如何在 Kotlin Native 中使用 Http Request 库