【问题标题】:HTTP 415 error in androidAndroid中的HTTP 415错误
【发布时间】:2014-05-01 13:12:59
【问题描述】:

我正在从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();
        }
    }

【问题讨论】:

    标签: android json wcf


    【解决方案1】:

    这个错误我是json错误什么的,我真的建议使用android JSONObject的json对象本身

    试试这个,我有一个 wcf 服务,我就是这样做的。

    JSONObject json = new JSONObject();
    
    json.put("key","value")
    
    StringEntity entity = new StringEntity(json.toString());
    

    注意:我真的推荐使用这个 chrome 扩展来测试你的 web 服务。您将在此使用的相同配置与 android post 方法相同。 Postman.

    【讨论】:

      【解决方案2】:

      这对我有用:

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

      【讨论】:

        猜你喜欢
        • 2020-12-11
        • 1970-01-01
        • 1970-01-01
        • 2019-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-14
        相关资源
        最近更新 更多