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
Stringurl= LoginUrl;
Stringresultstring="";
HttpClienthttpclient=newDefaultHttpClient();
HttpPosthttppost=newHttpPost(url);
// Add your data
List<NameValuePair> nameValuePairs = newArrayList<NameValuePair>(5);
nameValuePairs.add(newBasicNameValuePair("j_username", username));
nameValuePairs.add(newBasicNameValuePair("j_password", password));
try {
httppost.setEntity(newUrlEncodedFormEntity(nameValuePairs));
HttpContextlocalContext=newBasicHttpContext();
localContext.setAttribute(ClientContext.COOKIE_STORE,
Util.cookieStore);
try {
HttpResponseresponse= httpclient.execute(httppost,
localContext);
intresponsecode= response.getStatusLine().getStatusCode();
if (responsecode == 200) {
Util.responsecode = responsecode;
resultstring = "Success";
InputStreamin= response.getEntity().getContent();
resultstring = Util.convertinputStreamToString(in);
} elseif (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"