Java - sending HTTP parameters via POST method easily

前端 未结 17 1729
借酒劲吻你
借酒劲吻你 2020-11-21 05:54

I am successfully using this code to send HTTP requests with some parameters via GET method

void sendRequest(String request)
{
            


        
17条回答
  •  臣服心动
    2020-11-21 06:37

    Hello pls use this class to improve your post method

    public static JSONObject doPostRequest(HashMap data, String url) {
    
        try {
            RequestBody requestBody;
            MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);
    
            if (data != null) {
    
    
                for (String key : data.keySet()) {
                    String value = data.get(key);
                    Utility.printLog("Key Values", key + "-----------------" + value);
    
                    mBuilder.addFormDataPart(key, value);
    
                }
            } else {
                mBuilder.addFormDataPart("temp", "temp");
            }
            requestBody = mBuilder.build();
    
    
            Request request = new Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build();
    
            OkHttpClient client = new OkHttpClient();
            Response response = client.newCall(request).execute();
            String responseBody = response.body().string();
            Utility.printLog("URL", url);
            Utility.printLog("Response", responseBody);
            return new JSONObject(responseBody);
    
        } catch (UnknownHostException | UnsupportedEncodingException e) {
    
            JSONObject jsonObject=new JSONObject();
    
            try {
                jsonObject.put("status","false");
                jsonObject.put("message",e.getLocalizedMessage());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            Log.e(TAG, "Error: " + e.getLocalizedMessage());
        } catch (Exception e) {
            e.printStackTrace();
            JSONObject jsonObject=new JSONObject();
    
            try {
                jsonObject.put("status","false");
                jsonObject.put("message",e.getLocalizedMessage());
            } catch (JSONException e1) {
                e1.printStackTrace();
            }
            Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
        }
        return null;
    }
    

提交回复
热议问题