POST JSON到webservice

时间:2015-04-01 22:43:28

标签: java android json post

我尝试连接到网络服务并使用此代码发布JSON,但我不知道我做错了什么。 [edit]我使用HTTPClient编写了同一个类并且它工作但是因为httpURLConnect是谷歌关注的,所以我改变了它以使用它。

问题是,我发送格式正确的json吗?是我以正确的方式将其发送到服务器的方式?我标记了问题区域 这是我用来连接和发布json的帮助类:

package com.example.connecttohtml;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;
import android.widget.Toast;


public class HtmlHelper {
    public static JSONArray getData(RequestPackage p){
        JSONArray jsonArray;
        BufferedReader readData = null;
        String uri = p.getUri();

        if(p.getMethod().equals("GET")){
            uri += "?" + p.getEncodedParams();
        }

        try{
            URL url = new URL(uri);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod(p.getMethod());
            conn.setRequestProperty("Content-Type", "application/json");

            Log.d("getParams", p.getEncodedParams().toString());
            JSONObject json = new JSONObject(p.getParams());
            String params = json.toString();

    ////THIS IS THE PART IM NOT SURE OF///////////////////////      
            if (p.getMethod().equals("POST")){

                conn.setDoOutput(true);
                OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
                Log.d("jsonPassed", params);
                writer.write(params);
                writer.flush();
            }
//////////////////////////////////////END///////

            StringBuilder sb = new StringBuilder();
            readData = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while((line = readData.readLine()) != null){
                sb.append(line + "\n");
            }
            jsonArray = new JSONArray(sb.toString());
            return jsonArray;

        }catch(Exception e){
            e.printStackTrace();
            return null;
        }finally{
            if(readData !=null){
                try {
                    readData.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

这是RequestPackage类的实现代码:

package com.example.connecttohtml;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class RequestPackage {
    private String uri;
    private String method = "GET";
    private Map<String, String> params = new HashMap<String, String>();
    public String getUri() {
        return uri;
    }
    public void setUri(String uri) {
        this.uri = uri;
    }
    public String getMethod() {
        return method;
    }
    public void setMethod(String method) {
        this.method = method;
    }
    public Map<String, String> getParams() {
        return params;
    }
    public void setParams(Map<String, String> params) {
        this.params = params;
    }

    public void setParam(String key, String value){
        params.put(key, value);
    }

    public String getEncodedParams(){
        StringBuilder sb = new StringBuilder();

        for(String key : params.keySet()){
            String value = null;
            try {
                value = URLEncoder.encode(params.get(key), "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if(sb.length()> 0 ){
                sb.append("&");
            }       
            sb.append(key + "=" + value);
        }
        return sb.toString();
    }//getEncodedParams
}

0 个答案:

没有答案