0

我尝试开发一个 Android 应用程序。在这个应用程序中,我需要向 PHP 页面发送一个 POST 请求。

我的代码在 Java 端:

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

清单.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>

我从很多网站上搜索过,代码不断进入 catch 块。我也使用了 HttpURLConnection 并且没有工作。你能帮我解决什么问题吗?

4

2 回答 2

4

使用以下代码。它工作正常

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();
    }
}
于 2013-06-18T11:25:31.820 回答
0

我的问题是我想在应用程序主线程中运行我的代码,而主线程不允许这样做。有几种方法可以解决这个问题,

  1. 用于AsyncTask执行后台操作
  2. 在新线程中运行代码
  3. 启用网络操作,MainActivity这是我现在选择的

    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().
                                                    detectNetwork().build();
    StrictMode.setThreadPolicy(policy);
    

更新

由于问题的名称,我想分享如何在android中进行Http调用以指导人们。有一些api:

并且有一个培训

于 2016-11-11T06:09:15.203 回答