0

我一直在尝试让一个简单的 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"); 更高,那应该可以吗?当我这样做时,我得到了错误:

异常:java.net.ProtocolException:连接已建立。

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

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

4

2 回答 2

0

Here is an example of how to post with a JSON Object:

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

And example of how to get

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();
        }
于 2014-08-08T16:21:05.640 回答
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);
于 2014-08-08T16:55:50.583 回答