Android HttpsURLConnection - 带参数的简单POST请求

时间:2014-08-08 15:44:02

标签: java android httpurlconnection httpsurlconnection

我一直试图让一个简单的Android客户端服务器应用程序工作,我只有麻烦。我希望有人能看到这段代码,看看我做错了什么,也许我做错了订单,或忘记了什么?只需添加相关部分

            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
            conn.addRequestProperty("Content-Type", "application/json");

            // set some made up parameters
            String str =  "{'login':'superman@super.com','password':'password'}";
            byte[] outputInBytes = str.getBytes("UTF-8");
            OutputStream os = conn.getOutputStream();
            os.write( outputInBytes );
            os.close();

            // connection.setDoOutput(true); //should trigger POST - move above -> crash
            conn.setRequestMethod("POST");  // explicitly set POST -move above so we can set params -> crash
            conn.setDoInput(true);

我得到的错误是

  

'异常:java.net.ProtocolException:方法不支持   请求正文:GET'

如果我只是在没有参数的情况下发出POST请求,那很好,所以我想我应该移动connection.setDoOutput(true);或conn.setRequestMethod(" POST");更高,这应该工作吗?当我这样做时,我得到错误:

  

exception:java.net.ProtocolException:已建立连接。

所以,如果我在添加参数之前尝试设置为POST它不起作用,如果我尝试在它没有工作之后这样做...我错过了什么?还有另一种方法我应该这样做吗?我是否错误地添加了参数?我一直在寻找一个简单的Android网络示例,我找不到任何东西,是否有任何官方Android网站的例子?我想做的只是一个非常基本的网络操作,这太令人沮丧了!

编辑:我需要使用HttpsURLConnection,原因不包括在上面的代码中 - 我需要进行身份验证,信任主机等等 - 所以如果可能的话,我真的正在寻找上述代码的潜在修复。

2 个答案:

答案 0 :(得分:0)

以下是如何使用JSON对象发布的示例:

JSONObject payload=new JSONObject();
        try {
            payload.put("password", params[1]);
            payload.put("userName", params[0]);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String responseString="";
        try 
        {
            HttpPost httpPost = new HttpPost("www.theUrlYouQWant.com");

            httpPost.setEntity(new StringEntity(payload.toString()));
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse response = new DefaultHttpClient().execute(httpPost);
            responseString = EntityUtils.toString(response.getEntity());
        } 
        catch (ClientProtocolException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

如何获得

的例子
String responseString = "";
        //check if the username exists
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet("www.theUrlYouQWant.com");
        ArrayList<String> existingUserName = new ArrayList<String>();
        try 
        {
              HttpResponse response = client.execute(httpGet);
              StatusLine statusLine = response.getStatusLine();
              int statusCode = statusLine.getStatusCode();
              if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                  builder.append(line);
                }
              } 
              else 
              {
                Log.e(ParseException.class.toString(), "Failed to download file");
              }
        } 
        catch (ClientProtocolException e) 
        {
            e.printStackTrace();
        } 
        catch (IOException e) 
        {
            e.printStackTrace();
        }

答案 1 :(得分:0)

我按照本教程进行了http调用:

http://www.androidhive.info/2012/01/android-json-parsing-tutorial/

没有任何问题,工作正常。

以下是我从示例中修改过的课程:

public class ServiceHandler {

    static String response = null;
    public final static int GET = 1;
    public final static int POST = 2;
    String TAG = ((Object) this).getClass().getSimpleName();

    public ServiceHandler() {

    }

    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     */
    public String makeServiceCall(String url, int method) {
        return this.makeServiceCall(url, method, null);
    }

    /**
     * Making service call
     *
     * @url - url to make request
     * @method - http request method
     * @params - http request params
     */
    public String makeServiceCall(String url, int method,
                                  List<NameValuePair> params) {
        try {
            // http client
            HttpParams httpParameters = new BasicHttpParams();
            // Set the timeout in milliseconds until a connection is established.
            // The default value is zero, that means the timeout is not used.
            int timeoutConnection = 2000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            // Set the default socket timeout (SO_TIMEOUT)
            // in milliseconds which is the timeout for waiting for data.
            int timeoutSocket = 2000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            HttpEntity httpEntity = null;
            HttpResponse httpResponse = null;

            // Checking http request method type
            if (method == POST) {
                HttpPost httpPost = new HttpPost(url);
                // adding post params
                if (params != null) {
                    httpPost.setEntity(new UrlEncodedFormEntity(params));
                }

                httpResponse = httpClient.execute(httpPost);

            } else if (method == GET) {
                // appending params to url
                if (params != null) {
                    String paramString = URLEncodedUtils
                            .format(params, "utf-8");
                    url += "?" + paramString;
                }
                Log.e("Request: ", "> " + url);
                HttpGet httpGet = new HttpGet(url);

                httpResponse = httpClient.execute(httpGet);

            }
            if (httpResponse != null) {
                httpEntity = httpResponse.getEntity();
            } else {
                Log.e(TAG, "httpResponse is null");
            }
            response = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return response;

    }
}

这就是我使用该类的方式:

nameValuePairs = new ArrayList<NameValuePair>();
String param_value = "value";
String param_name = "name";
nameValuePairs.add(new BasicNameValuePair(param_name, param_value));

// Creating service handler class instance
sh = new ServiceHandler();

String json = sh.makeServiceCall(Utils.getUrl, ServiceHandler.GET, nameValuePairs);