Problems With A Build_httpbody() // Httppost.setentity() - Android
I develop AndroidApps with AndroidStudio I start to do a simple HttpPost Request and I had a problems, all post that I could find do this: private void CheckLoguin_Request(String U
Solution 1:
Updated 2016
Using HttpURLConnection class we need to open BufferedWritter to insert our entity values as the following code:
//Declaration of variablesprivate List<NameValuePair> ListOfValues;
...
publicCheck_Loguin_Request(Context cx,String url, List<NameValuePair> ListOfValues)
{
this.cx = cx;
this.Url = url;
this.ListOfValues= ListOfValues;
}
@Overrideprotected String doInBackground(String... strings) {
//Declaration of variablesInputStreamis=null;
StringResult="";
URLurll=newURL(url);
HttpURLConnectionconn= (HttpURLConnection) urll.openConnection();
conn.setReadTimeout(10000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStreamos= conn.getOutputStream();
BufferedWriterwriter=newBufferedWriter(newOutputStreamWriter(os, "UTF-8"));
writer.write(Build_HttpBody(ListOfValues));
writer.flush();
writer.close();
os.close();
// Starts request
conn.connect();
intResponseCode= conn.getResponseCode();
if (ResponseCode == 200) {
is = conn.getInputStream();
StringEntityResult= ReadResponse_HttpURLConnection(is);
}
else {
thrownewRuntimeException("Invalid Status Code");
}
}
Attention the DefaultHttpClient class is deprecated (2011)
For more info following this link.
Try to use this following code, remember for this case always use AsyncTask:
privateclassCheck_Loguin_RequestextendsAsyncTask <String,Void,String>{
Context cx;
String Url;
List<NameValuePair> BodyRequest_Elements;
publicCheck_Loguin_Request(Context cx,String url, List<NameValuePair> ListOfValues)
{
this.cx = cx;
this.Url = url;
this.BodyRequest_Elements = ListOfValues;
}
private String convertStreamToString(InputStream is) {
BufferedReaderreader=newBufferedReader(newInputStreamReader(is));
StringBuildersb=newStringBuilder();
Stringline=null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
@Overrideprotected String doInBackground(String... strings) {
//Declaration of variables
DefaultHttpClient httpClient;
HttpPostRequest=newHttpPost(url_Loguin);
HttpResponse Response;
HttpParamshttpParameters=newBasicHttpParams();
httpParameters.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
// Set the timeout in milliseconds until a connection is established.// The default value is zero, that means the timeout is not used.inttimeoutConnection=3000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)// in milliseconds which is the timeout for waiting for data.inttimeoutSocket=5000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpClient = newDefaultHttpClient(httpParameters);
try {
HttpEntityentity=newUrlEncodedFormEntity(BodyRequest_Elements);
Request.setHeader(entity.getContentType());
Request.setEntity(entity);
Response = httpClient.execute(Request);
if(Response.getStatusLine().getStatusCode() == 200){
StringEntityResult= EntityUtils.toString(Response.getEntity());
//HttpEntity EntityResult = Response.getEntity();//InputStream iStream = EntityResult.getContent();//JSONObject json = new JSONObject(convertStreamToString(iStream));
EntityResult = EntityResult.replaceAll("[()]", "");
JSONObjectjson=newJSONObject(EntityResult);
StringResult= json.optString("code").toString();
return Result;
}
else{
thrownewRuntimeException("Invalid Status Code");
}
}
catch (Exception ex){
Log.getStackTraceString(ex);
return ex.toString();
}
}
}
Solution 2:
You are obviously not handling the IO exceptions being thrown from the constructor:
see: Android docs on UrlEncodedFormEntity
What puzzles me is that your IDE is not reporting this, or how this code even compiles, let alone runs/debugs.
Edit: If you are new at this stuff, maybe it would be worth to take a look at: Android Volley , which is a quite simple yet effective library developed by Google for Android networking.
Post a Comment for "Problems With A Build_httpbody() // Httppost.setentity() - Android"