我想使用 Android 向某个 url 发送 http 请求。
我是一名 iOS 开发人员,现在正在尝试学习 Android。
我曾经在 iOS 中发送 JSON
字符串,如下所示
{"function":"login", "parameters": {"username": "nithin""password": "123456"}}
如何在 Android 中发送此信息?
我尝试了 List<NameValuePair>
但找不到正确的解决方案。
我尝试过的完整代码 -
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(URL);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("function", "login"));
nameValuePairs.add(new BasicNameValuePair("username", "nithin"));
nameValuePairs.add(new BasicNameValuePair("password", "123456"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
最佳答案
我认为 JsonStringer 对您来说既简单又有用。
试试这个:
HttpPost request = new HttpPost(URL);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
JSONStringer vm;
try {
vm = new JSONStringer().object().key("function")
.value(login).key("parameters").object()
.key("username")
.value(nithin).key("password").value("123456")
.endObject().endObject();
StringEntity entity = new StringEntity(vm.toString());
request.setEntity(entity);
HttpClient httpClient = new DefaultHttpClient();
HttpResponse response = httpClient.execute(request);
关于java - 在android中使用List<NameValuePair>创建一个json字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21482378/