Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java HttP Post方法不工作_Java_Android - Fatal编程技术网

Java HttP Post方法不工作

Java HttP Post方法不工作,java,android,Java,Android,我试着用这种方法,我也试着取消诽谤,但都是徒劳的。请帮帮我。我的andriod studio上没有显示任何HTTPClient库。我们将不胜感激 public String getHttpPost(String url,ContentValues) { StringBuilder str = new StringBuilder(); HttpClient client = new DefaultHttpClient(); HttpPost ht

我试着用这种方法,我也试着取消诽谤,但都是徒劳的。请帮帮我。我的andriod studio上没有显示任何HTTPClient库。我们将不胜感激

 public String getHttpPost(String url,ContentValues) {
        StringBuilder str = new StringBuilder();

        HttpClient client = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(params));
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) { // Status OK
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    str.append(line);
                }
            } else {
                Log.e("Log", "Failed to download result..");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return str.toString();
    }

哦!!您仍然在使用HttpClient。您可以使用HttpURLConnection、Volley等。HttpClient类现在已被弃用。还要在gradle文件中添加Internet权限和依赖项

 HttpURLConnection urlConnection = null;
                try {
                    URL urlToRequest = new URL(_url);
                    urlConnection = (HttpURLConnection) urlToRequest.openConnection();
                    urlConnection.setConnectTimeout(30000);
                    urlConnection.setReadTimeout(30000);
                    urlConnection.setDoOutput(true);
                    urlConnection.setDoInput(true);
                    urlConnection.setRequestProperty("Content-Type", "application/json");
                    urlConnection.setRequestProperty("Accept", "application/json");

                    if (_authenticationKey != null) {
                        urlConnection.setRequestProperty(_authenticationKey, _authenticationValue);
                    }
                    if (_jsonPacket != null) {
                        OutputStreamWriter wr = new OutputStreamWriter(urlConnection.getOutputStream());
                        wr.write(_jsonPacket);
                        wr.flush();
                    }

                    int statusCode = urlConnection.getResponseCode();

                    JSONObject job;
                    if (statusCode != HttpURLConnection.HTTP_OK) {
                        InputStream in = new BufferedInputStream(urlConnection.getErrorStream());
                        String responseString = getResponseString(in);
                        if (isJSONValid(responseString)) {
                            job = new JSONObject(responseString);
                            return new PostingResult(job, Constants.IntegerConstants.failureFromWebService, "");
                        } else {
                            return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + "Response code = " + statusCode);
                        }

                    } else {
                        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
                        String responseString = getResponseString(in);
                        if (isJSONValid(responseString)) {
                            job = new JSONObject(responseString);
                            return new PostingResult(job, Constants.IntegerConstants.success, "");
                        } else {
                            return new PostingResult(null, statusCode, Constants.StringConstants.serverCommunicationFailed + Constants.StringConstants.serverReadingResponseFailed);
                        }
                    }
您可以使用“截击”库进行网络呼叫

例如

  • 在build.gradle(模块:app)中添加此行

    编译'com.mcxiaoke.volley:library:1.0.19'

  • 当您拨打网络电话时,您需要互联网许可。因此,在Manifest.xml中添加Internet权限行

  • 现在,您需要在类中编写一个小方法,在该方法中,您需要进行网络调用并向其传递Hashmap。Hashmap包含所有post参数

    private void getJSONResponse(HashMap<String, String> map, String url) {
            pd.show();
            JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, new JSONObject(map), new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d("Mayur", "Response : " + response);
                    //tv_res.setText(response.toString());
                    //pd.dismiss();
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this, "Error Occured", Toast.LENGTH_SHORT).show();
                    //tv_res.setText("ERROR");
                    //pd.dismiss();
                }
            });
    request.setRetryPolicy(new DefaultRetryPolicy(20000,DefaultRetryPolicy.DEFAULT_MAX_RETRIES,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));Volley.newRequestQueue(this).add(request);}
    
    private void getJSONResponse(HashMap映射,字符串url){
    pd.show();
    JsonObjectRequest=新的JsonObjectRequest(request.Method.POST、url、新的JSONObject(map)、新的Response.Listener(){
    @凌驾
    公共void onResponse(JSONObject响应){
    日志d(“Mayur”,“响应:”+响应);
    //tv_res.setText(response.toString());
    //pd.解散();
    }
    },new Response.ErrorListener(){
    @凌驾
    公共无效onErrorResponse(截击错误){
    Toast.makeText(MainActivity.this,“发生错误”,Toast.LENGTH_SHORT.show();
    //tv_res.setText(“错误”);
    //pd.解散();
    }
    });
    request.setRetryPolicy(新的DefaultRetryPolicy(20000,DefaultRetryPolicy.DEFAULT\u MAX\u RETRIES,DefaultRetryPolicy.DEFAULT\u BACKOFF\u MULT));Volley.newRequestQueue(this).add(request);}
    
  • 现在,在onCreate方法或任何其他方法中,只需创建post参数的Hashmap,并将其与post url一起传递给此方法

    例如

    HashMap map=newhashmap();
    地图放置(“fname”、“Mayur”);
    地图放置(“lname”、“Thakur”);
    getJSONResponse(map,);
    
    您是否在gradle文件中添加了依赖项?您是否在AndroidManifeat.xml中添加了Internet权限?您是否希望使用其他方法进行网络调用,例如,使用库(如volley或Reformation)?是的,我添加了所有我添加了Internet权限,还添加了依赖项
    HashMap<String, String> map = new HashMap<String, String>();
            map.put("fname", "Mayur");
            map.put("lname", "Thakur");
    getJSONResponse(map,<your url>);