Android - http post返回null响应

时间:2015-06-22 13:02:45

标签: android

我是Android的新手,我尝试使用参数发布到Web App。 但是,我的代码不起作用。来自Web App的“响应”始终为空。

以下是我的代码,点击了Android应用的按钮:

    final int TIMEOUT_MS = 3000;
    EditText editName, editPwd;

    String actionURL, user, pwd, user_field, pwd_field;


    actionURL = "http://www.posttestserver.com/post.php";



    user_field = "loginId";
    pwd_field = "passwd";

    editName = (EditText)findViewById(R.id.txtName);
    user = editName.getText().toString();

    editPwd = (EditText)findViewById(R.id.txtPassword);
    pwd = editPwd.getText().toString();


    HttpParams params = new BasicHttpParams();
    HttpClient httpClient = new DefaultHttpClient(params);
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
    HttpPost httpPost = new HttpPost(actionURL); 

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
    nameValuePairs.add(new BasicNameValuePair(user_field, user));  
    nameValuePairs.add(new BasicNameValuePair(pwd_field, pwd));


    HttpResponse endA = null;
    String endResult = null;

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpClient.execute(httpPost);
        endA = response;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

4 个答案:

答案 0 :(得分:1)

您应该考虑使用第三方库来帮助您处理http请求。例如okhttp(http://square.github.io/okhttp/)。它允许你有一个更清洁的呼叫api:

 RequestBody formBody = new FormEncodingBuilder()
    .add("search", "Jurassic Park")
    .build();
Request request = new Request.Builder()
    .url("https://en.wikipedia.org/w/index.php")
    .post(formBody)
    .build();

Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

System.out.println(response.body().string());

答案 1 :(得分:1)

Http必须在第二个线程中完成。

Runnable run = new Runnable() {
        @Override
        public void run() {
            try {
                //your http post code here
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                            //any updates to user interface here
                    }

                });

            } catch (Exception e) {

            }
        }
    };
    Thread thread = new Thread(run);
    thread.start();

此外,涉及响应的所有代码必须在该线程中完成,并且必须将对ui的更新发布到处理程序。别忘了在清单中请求互联网许可。

另一个选择是使用IntentService类。这是繁重的背景工作的理想选择。

https://developer.android.com/training/run-background-service/create-service.html

答案 2 :(得分:0)

Sub ProcessRemittance()

    'Each variable needs a type - otherwise they're variants.
    Dim remitDate As Date, remitNumber As Long, myString As String, tempString As String
    Dim myRange As Range, cell As Range
    Dim StringArray As Variant
    Dim x As Long

    On Error GoTo ERROR_HANDLER

    With ActiveWorkbook.Worksheets("Sheet1")

        .Range("A1:A10").SpecialCells(xlCellTypeBlanks).EntireRow.Delete

        For x = 10 To 1 Step -1
            myString = Left(.Cells(x, 1), 3)

            If myString <> "00 " Then
                .Cells(x, 1).EntireRow.Delete
            End If
        Next x

    End With

    On Error GoTo 0
    Exit Sub

ERROR_HANDLER:
    Select Case Err.Number
        Case 1004 'No cells were found (occurs if SpecialCells returns nothing).
            Err.Clear
            Resume Next
        Case Else
            MsgBox "Error " & Err.Number & vbCr & _
                " (" & Err.Description & ") in procedure ProcessRemittance."
            Err.Clear
    End Select

End Sub

答案 3 :(得分:0)

我尝试在线程中运行我的代码,如下所示,但由于Activity / Intent语句,我甚至没有编译代码(我希望显示要在WebView中显示的http post响应)。

public void loginClick(View view)
{

    new Thread( new Runnable() {
        @Override
        public void run() {


    final int TIMEOUT_MS = 30000;
    EditText editName, editPwd;

    String actionURL, user, pwd, user_field, pwd_field;


    actionURL = "http://www.posttestserver.com/post.php";

// user_field =“q”;

    user_field = "loginId";
    pwd_field = "passwd";

    editName = (EditText)findViewById(R.id.txtName);
    user = editName.getText().toString();

    editPwd = (EditText)findViewById(R.id.txtPassword);
    pwd = editPwd.getText().toString();

// user =“test”;  // pwd =“steve”;

    HttpParams params = new BasicHttpParams();
    HttpClient httpClient = new DefaultHttpClient(params);
    HttpConnectionParams.setConnectionTimeout(httpClient.getParams(), TIMEOUT_MS);
    HttpConnectionParams.setSoTimeout(httpClient.getParams(), TIMEOUT_MS);
    HttpPost httpPost = new HttpPost(actionURL); 

    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
    nameValuePairs.add(new BasicNameValuePair(user_field, user));  
    nameValuePairs.add(new BasicNameValuePair(pwd_field, pwd));


    HttpResponse endA = null;
    String endResult = null;

    try {
        httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpClient.execute(httpPost);

        endA = response;
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } 

    BasicResponseHandler myHandler = new BasicResponseHandler();

    try {
        endResult = myHandler.handleResponse(endA);
    } catch (HttpResponseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


    Intent myWebViewIntent = new Intent(this, MyWebView.class);
    myWebViewIntent.putExtra("htmlString", endResult);
    startActivity(myWebViewIntent);


    }

}).start();

} }