HttpUrlConnection With Post Request And Parameter As Json Object Android
Hi I am developing small android application in which I want to use HttpUrlConnection post request with params as json object. But its not working for me I did it in following way:
Solution 1:
This error occurs due to 401 responsecode.
You can check first response code like this
int responsecode = response.getStatusLine().getStatusCode();
This exception is thrown if the server replies with a 401.
The actual cause for the 401 that you didn't send an OAuth verifier code where it was expected at this point.
You can refer below code
String url = LoginUrl;
String resultstring = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(5);
nameValuePairs.add(new BasicNameValuePair("j_username", username));
nameValuePairs.add(new BasicNameValuePair("j_password", password));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpContext localContext = new BasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,
Util.cookieStore);
try {
HttpResponse response = httpclient.execute(httppost,
localContext);
int responsecode = response.getStatusLine().getStatusCode();
if (responsecode == 200) {
Util.responsecode = responsecode;
resultstring = "Success";
InputStream in = response.getEntity().getContent();
resultstring = Util.convertinputStreamToString(in);
} else if (responsecode == 401) {
Util.responsecode = responsecode;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Solution 2:
I higly recommend using Unirest its a simple library for making http requests it has a very easy to use api and it doesnt overload the mem too much, here's an example on how would it be using your example code.
Unirest.post("https://example.com")
.queryString("places", "['LNCf206KYa5b', 'oWdC0hnm1jjJ']")
.queryString("action", "Do")
.asJson()
Post a Comment for "HttpUrlConnection With Post Request And Parameter As Json Object Android"