2012-11-06 18 views
18
import java.io.BufferedReader;  
import java.io.InputStreamReader;  
import java.net.HttpURLConnection;  
import java.net.URL;  
import java.io.DataOutputStream;   
import java.io.InputStream; 

public class TestingPost { 

public static void main(String args[]) { 

    URL url; 
    HttpURLConnection connection = null; 
    String targetURL=".....";//here is my local server url 
    String urlParameters="{\"clubhash\":\"100457d41b9-ab22-4825-9393-ac7f6e8ff961\",\"username\":\"anonymous\",\"message\":\"simply awesome\",\"timestamp\":\"2012/11/05 13:00:00\"}"; 

    try { 
     //Create connection 
     url = new URL(targetURL); 
     connection = (HttpURLConnection)url.openConnection(); 
     connection.setRequestMethod("POST"); 
     connection.setRequestProperty("Content-Type", 
      "application/x-www-form-urlencoded"); 

     connection.setRequestProperty("Content-Length", "" + 
       Integer.toString(urlParameters.getBytes().length)); 
     connection.setRequestProperty("Content-Language", "en-US"); 

     connection.setUseCaches (false); 
     connection.setDoInput(true); 
     connection.setDoOutput(true); 

     //Send request 
     DataOutputStream wr = new DataOutputStream (
        connection.getOutputStream()); 
     wr.writeBytes (urlParameters); 
     wr.flush(); 
     wr.close(); 

     //Get Response  
     InputStream is = connection.getInputStream(); 
     BufferedReader rd = new BufferedReader(new InputStreamReader(is)); 
     String line; 
     StringBuffer response = new StringBuffer(); 
     while((line = rd.readLine()) != null) { 
     response.append(line); 
     response.append('\r'); 
     } 
     rd.close(); 
     System.out.println("message="+response.toString()); 

    } catch (Exception e) { 

     e.printStackTrace(); 

    } finally { 

     if(connection != null) { 
     connection.disconnect(); 
     } 
    } 
    } 

} 

का उपयोग कर JSON ऑब्जेक्ट भेजते समय HTTP POST विधि का उपयोग कर JSON ऑब्जेक्ट भेजने की कोशिश कर रहा हूं। ऊपर कोड है लेकिन मुझेHTTP 415 POST

java.io.IOException: Server returned HTTP response code: 415 for URL: .... 
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) 
at TestingPost.main(TestingPost.java:38)" 

मेरे कोड में क्या गलत है?

उत्तर

36

HTTP प्रतिक्रिया कोड आपको मिल

415 Unsupported Media Type 

इसका मतलब यह है कि सर्वर प्रारूप आप इसे करने के लिए भेजा नहीं संभाल सकता है। आपका HTTP अनुरोध इस हेडर को सेट करता है:

Content-Type: application/x-www-form-urlencoded 

यह फ़ॉर्म सबमिट किए जाने पर ब्राउज़र द्वारा भेजा गया सामग्री प्रकार है। आप JSON भेजने के लिए चाहते हैं, तो इस शीर्षक का प्रयोग:

Content-Type: application/json 
+0

धन्यवाद, यह वास्तव में काम करता है !!! –

0

मैं सही ढंग से

Content-Type: application/json 

गुजर रहा था लेकिन मेरे सर्वर अभी भी अनुरोध को अस्वीकार किया गया था क्योंकि मैं भी

Accept: application/json 

गुजर रहा था कौन सा मेरे मामले में अनुमति नहीं थी।

संबंधित मुद्दे