2016-09-30 144 views
1

我试图用这样的POST指令:在我的Android应用的Android POST使用HTTP URL请求

http://123.456.78.9/Dev/SignIn?Username=email%40google.edu&Password=thePassword

,我已经看了之类的HttpConnection但我米仍然不知道什么是最好的方式来打这样的电话,我需要包括多个键和值。

我想这个现在:

   URl url = new URL("http://123.456.78.9/Dev/SignIn?");  
       HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); 
       conn.setReadTimeout(10000); 
       conn.setConnectTimeout(15000); 
       conn.setRequestMethod("POST"); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 

       List<NameValuePair> params = new ArrayList<NameValuePair>(); 
       params.add(new BasicNameValuePair("email", emailText)); 
       params.add(new BasicNameValuePair("Password", passwordText)); 
       OutputStream os = conn.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8")); 
       writer.write(getQuery(params)); 
       writer.flush(); 
       writer.close(); 
       os.close(); 

这会做的工作?如果我要使用这种方法,我该如何去获得答案?

+0

貌似你试图做一个GET请求,不POST请求,如你有查询字符串中的参数.... –

+0

看看这里的答案:http://stackoverflow.com/questions/33030660/jsonparser-from-androidhive-tutorial-nosuchmethoderror-in-defaulthttpclient –

+0

看看android库提供简单和强大的工作与http连接ction。 [volley](https://developer.android.com/training/volley/index.html)[okhttp](http://square.github.io/okhttp/)[retofit with okhttp](http:// square.github.io/retrofit/) –

回答

-1

可以使用Android Asynchronous Http Client library

final AsyncHttpClient asyncHttpClient=new AsyncHttpClient(); 
    //Add Parameter 
    RequestParams requestParams=new RequestParams(); 
    requestParams.put("email", emailText); 
    requestParams.put("Password", passwordText); 

    //Chose one from two method in below 

    //send with get method 
    asyncHttpClient.get("http://123.456.78.9/Dev/SignIn", requestParams, new TextHttpResponseHandler() { 
     @Override 
     public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 

     } 

     @Override 
     public void onSuccess(int statusCode, Header[] headers, String responseString) { 
      System.out.println(responseString); 
     } 
    }); 

    //send with post method 
    asyncHttpClient.post("http://123.456.78.9/Dev/SignIn", requestParams, new TextHttpResponseHandler() { 
     @Override 
     public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) { 

     } 

     @Override 
     public void onSuccess(int statusCode, Header[] headers, String responseString) { 
      System.out.println(responseString); 
     } 
    }); 

但您必须在您添加的gradle这个库

compile 'com.loopj.android:android-async-http:1.4.9'