Android Post Request To Php
I try to develope an Android application. In this application, I need to send a POST request to a PHP page. My code is at Java side: DefaultHttpClient httpclient = new DefaultHttp
Solution 1:
Use the following code. It is working fine
publicclassHttpClient {
privatestaticfinalStringTAG="HttpClient";
publicstatic JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {
try {
DefaultHttpClienthttpclient=newDefaultHttpClient();
HttpPosthttpPostRequest=newHttpPost(URL);
StringEntity se;
se = newStringEntity(jsonObjSend.toString());
httpPostRequest.setEntity(se);
httpPostRequest.setHeader("Accept", "application/json");
httpPostRequest.setHeader("Content-type", "application/json");
httpPostRequest.setHeader("Accept-Encoding", "gzip");
longt= System.currentTimeMillis();
HttpResponseresponse= (HttpResponse) httpclient.execute(httpPostRequest);
Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");
HttpEntityentity= response.getEntity();
if (entity != null) {
InputStreaminstream= entity.getContent();
HeadercontentEncoding= response.getFirstHeader("Content-Encoding");
if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
instream = newGZIPInputStream(instream);
}
String resultString= convertStreamToString(instream);
instream.close();
resultString = resultString.substring(0,resultString.length()-1);
JSONObjectjsonObjRecv=newJSONObject(resultString);
Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");
return jsonObjRecv;
}
}
catch (Exception e)
{
Log.e("Exception", "Exception");
e.printStackTrace();
}
returnnull;
}
privatestatic 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();
}
}
Solution 2:
My problem was that I want to run my code in application main thread and main thread doesn't allow that. There are a few ways to solve this problem,
- Using
AsyncTaskto perform background operation - Run the code in a new thread
Enable network operation in
MainActivityand this is what I choose for now byStrictMode.ThreadPolicypolicy=newStrictMode.ThreadPolicy.Builder(). detectNetwork().build(); StrictMode.setThreadPolicy(policy);
UPDATE
Because of the name of the question I want to share how to make Http call in android in order to guide people. There are some apis:
And there is a training in
Post a Comment for "Android Post Request To Php"