android中的HTTP 415错误

时间:2014-05-01 13:13:00

标签: android json wcf

我从http://ashapurasoftech.com/train/test.json获取代码并将其以JSON格式发布到WCF服务。但是,我的代码中出现“415 Unsupported Media”错误。

谁能告诉我在哪里做出改变?

以下是我的代码:

public class S1 extends ListActivity implements OnClickListener {
    private static String url = "http://ashapurasoftech.com/train/test.json";
    private static final String TAG_a = "menu",TAG_Name = "Name",TAG_Cat = "Category";

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.table1);

        lv =getListView();
        category_main = "";

        new Getitems().execute(category_main);

        sub = (Button) findViewById(R.id.submit);
        sub.setOnClickListener(this);

        b =(Button) findViewById(R.id.start);
        b.setOnClickListener(this);

        itemList = new ArrayList<HashMap<String, String>>();
    }

    @Override
    public void onClick(View arg0) {
        switch(arg0.getId()){
            case R.id.start:
                try {
                    Log.d("start","click");
                    onbuttonclick();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                break;
            case R.id.submit:
                Log.d("submi","click");
                onsubmitclick();
                break;
        }
    }

    private void onsubmitclick() {
        Log.d("submi inside","click");
        {
            new Thread()
            {
                public void run(){
                    try {
                        EditText et = (EditText) findViewById(R.id.EditText05);
                        EditText et1 = (EditText) findViewById(R.id.EditText06);
                        TextView tx= (TextView) findViewById(R.id.name);

                        et.getText();
                        et1.getText();
                        tx.getText();

                        boolean isValid = true;

                        if (isValid) {
                            // POST request 
                            HttpPost request = new HttpPost("http://192.168.0.119:5204/Service1.svc/GetOrder");
                            request.setHeader("Accept", "application/json; charset=utf-8");
                            request.setHeader("Content-type", "application/json; charset=utf-8");

                            // Build JSON string
                            String json = "{'Order':[";

                            if(!et.equals(str)){
                                String stra = "{'Table_id':"+Second.a+",'item_name':'"+tx.getText()+"','Item_quantity':'"+et.getText()+"','Item_additionaldetails':'"+et1.getText()+"'}";
                                json = json+stra;
                            }
                            json = json + "]}";

                            Log.d("",""+json);

                            StringEntity entity = new StringEntity(json.toString());

                            request.setEntity(entity);

                            // Send request to WCF service
                            DefaultHttpClient httpClient = new DefaultHttpClient();

                            HttpResponse response = httpClient.execute(request);

                            Log.d("response:", "Saving : "
                                + response.getStatusLine().getStatusCode());
                        } 
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }.start();
        }
    }

2 个答案:

答案 0 :(得分:0)

这个错误我是一个json错误或其他什么,我真的建议使用json对象perse by android JSONObject

试试这个,我得到了一个wcf服务,这就是我的工作方式。

JSONObject json = new JSONObject();

json.put("key","value")

StringEntity entity = new StringEntity(json.toString());

注意:我真的建议使用此chrome extenxion来测试您的Web服务。您在此上使用的相同配置在android post方法上是相同的。 Postman

答案 1 :(得分:0)

这对我有用:

private DefaultHttpClient mHttpClient;
Context context;
public String error = "";

//Contrutor para que metodos possam ser usados fora de uma activity
public HTTPconector(Context context) {
    this.context = context;
}


public HTTPconector() {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    mHttpClient = new DefaultHttpClient(params);
}


public void FileClientPost(String txtUrl, File file){
    try
    {
        error = "";
        HttpPost httppost = new HttpPost(txtUrl);
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        multipartEntity.addPart("Image", new FileBody(file));
        httppost.setEntity(multipartEntity);
        mHttpClient.execute(httppost, new PhotoUploadResponseHandler());
    }
    catch (Exception e)
    {
        Log.e(HTTPconector.class.getName(), e.getLocalizedMessage(), e);
        e.getStackTrace();
        error = e.getMessage();
    }
}

//Verifica se a rede esta disponível
public boolean isNetworkAvailable() {
    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = cm.getActiveNetworkInfo();
    // if no network is available networkInfo will be null
    // otherwise check if we are connected
    if (networkInfo != null && networkInfo.isConnected()) {
        return true;
    }
    return false;
}

public String Get(String txtUrl){
    try {
        URL url = new URL(txtUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setReadTimeout(10000);
        con.setConnectTimeout(15000);
        con.setRequestMethod("GET");
        con.setDoInput(true);
        con.connect();

        return readStream(con.getInputStream());

    }  catch (ProtocolException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    }
}


public String Post(String txtUrl){
    File image;

    try {
        URL url = new URL(txtUrl);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("POST");
        con.setDoInput(true);
        con.setDoOutput(true);
        con.connect();

        //con.getOutputStream().write( ("name=" + "aa").getBytes());

        return readStream(con.getInputStream());
    } catch (ProtocolException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    } catch (IOException e) {
        e.printStackTrace();
        return "ERRO: "+e.getMessage();
    }
}


//Usado para fazer conexão com a internet
public String conectar(String u){
    String resultServer = "";
    try {
        URL url = new URL(u);
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        resultServer = readStream(con.getInputStream());
    } catch (Exception e) {
        e.printStackTrace();
        resultServer = "ERRO: "+ e.getMessage();
    }

    Log.i("HTTPMANAGER: ", resultServer);
    return resultServer;
}

//Lê o resultado da conexão
private String readStream(InputStream in) {
    String serverResult = "";
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }

        serverResult = reader.toString();
    }   catch (IOException e) {
        e.printStackTrace();
        serverResult = "ERRO: "+ e.getMessage();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
                serverResult = "ERRO: "+ e.getMessage();
            }
        }
    }
    return  serverResult;
}

private class PhotoUploadResponseHandler implements ResponseHandler<Object>
{
    @Override
    public Object handleResponse(HttpResponse response)throws ClientProtocolException, IOException {

        HttpEntity r_entity = response.getEntity();
        String responseString = EntityUtils.toString(r_entity);
        Log.d("UPLOAD", responseString);
        return null;
    }
}