我正在发送以下JSON请求;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email",username));
params.add(new BasicNameValuePair("password",pass));
JSONObject json = jParser.makeHttpRequest(url_login, "POST", params);
它生成以下字符串email=xxx, password=xxxx
,但我希望生成的字符串为JSON格式(即"email":"xxx","password":"xxxx"
)。我怎样才能做到这一点?
您要在代码中使用的东西是一个调用,它将数据发布到服务器中raw-data format
。使用下面的代码我的工作:
public String POST(String url, JSONObject jsonObject) {
InputStream inputStream = null;
String result = "";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
String json = "";
json = jsonObject.toString();
StringEntity se = new StringEntity(json);
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
HttpResponse httpResponse = httpclient.execute(httpPost);
inputStream = httpResponse.getEntity().getContent();
if (inputStream != null)
result = convertInputStreamToString(inputStream);
else
result = "Did not work!";
} catch (Exception e) {
Log.d("InputStream", e.getLocalizedMessage());
}
return result;
}
private static String convertInputStreamToString(InputStream inputStream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
String result = "";
while ((line = bufferedReader.readLine()) != null)
result += line;
inputStream.close();
return result;
}
现在,当您要使用数据或将数据发布到服务器时,您需要使用以下内容:
JSONObject jsonObject = new JSONObject();
jsonObject.put("email",username));
jsonObject.put("password",pass);
现在您需要使用
String request = POST(yourURL , jsonObject);
注意:在使用此找你raw-data format
,那么你应该设置Content-Type
到application/json
你的back-end
侧面,否则将无法正常工作。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句