繁体   English   中英

Android中的HTTP 415错误

[英]HTTP 415 error in android

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

谁能告诉我在哪里进行更改?

下面是我的代码:

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

这个错误我可能是json错误之类的东西,我真的建议使用android JSONObject的json对象本身

试试这个,我得到了wcf服务,这就是我的方法。

JSONObject json = new JSONObject();

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

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

注意:我真的建议您使用此Chrome扩展来测试您的Web服务。 您将在此使用的相同配置与android post方法相同。 邮递员

这对我有用:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM