我想使用Android向网址发送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
}
答案 0 :(得分:2)
我觉得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);