Android POST Request to PHP

穿精又带淫゛_ 提交于 2019-12-12 00:37:19

问题


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 DefaultHttpClient();
 HttpPost httppost = new HttpPost("http://localhost/get.php");

     ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
     nameValuePairs.add(new BasicNameValuePair("mail", "asdasd"));
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

     try{
            HttpResponse httpresponse = httpclient.execute(httppost);

     }catch(Exception e){
         Toast.makeText(getApplicationContext(), "Didn't Happen",10).show();    
     }

Manifest.xml

 <?
xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.misman"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="10" android:targetSdkVersion="17"/>
    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:permission="android.permission.INTERNET"
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.misman.MainActivity"
            android:label="@string/app_name" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

I have searched from a lot of websites and the code goes in catch block continuously.I also used HttpURLConnection and didn't work. Can you help me what can be the problem?


回答1:


Use the following code. It is working fine

public class HttpClient {
    private static final String TAG = "HttpClient";

    public static JSONObject SendHttpPost(String URL, JSONObject jsonObjSend) {

    try {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        HttpPost httpPostRequest = new HttpPost(URL);

        StringEntity se;
        se = new StringEntity(jsonObjSend.toString());

        httpPostRequest.setEntity(se);
        httpPostRequest.setHeader("Accept", "application/json");
        httpPostRequest.setHeader("Content-type", "application/json");
        httpPostRequest.setHeader("Accept-Encoding", "gzip"); 

        long t = System.currentTimeMillis();
        HttpResponse response = (HttpResponse) httpclient.execute(httpPostRequest);
        Log.i(TAG, "HTTPResponse received in [" + (System.currentTimeMillis()-t) + "ms]");

        HttpEntity entity = response.getEntity();

        if (entity != null) {
            InputStream instream = entity.getContent();
            Header contentEncoding = response.getFirstHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                instream = new GZIPInputStream(instream);
            }

            String resultString= convertStreamToString(instream);
            instream.close();
            resultString = resultString.substring(0,resultString.length()-1); 

            JSONObject jsonObjRecv = new JSONObject(resultString);
            Log.i(TAG,"<JSONObject>\n"+jsonObjRecv.toString()+"\n</JSONObject>");

            return jsonObjRecv;
        } 

    }
    catch (Exception e)
    {
        Log.e("Exception", "Exception");
        e.printStackTrace();
    }
    return null;
}


private static String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = 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();
    }
}



回答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,

  1. Using AsyncTask to perform background operation
  2. Run the code in a new thread
  3. Enable network operation in MainActivity and this is what I choose for now by

    StrictMode.ThreadPolicy policy = new StrictMode.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:

  • Volley
  • Retrofit

And there is a training in

  • Android Developer


来源:https://stackoverflow.com/questions/17167338/android-post-request-to-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!