服务器返回HTTP响应代码:400为URL我怀疑不是URL问题

时间:2014-10-02 23:43:29

标签: java json

请在下面考虑我的JAVA程序(Servlet)。出于某种原因,我继续为PUT和POST获取以下错误,因为GET在相同的HTTP URL下正常工作(当然,在GET方面我没有发送任何内容的一些小的改动)。

因此,我感觉网址可能不是问题,因为它正在使用GET。

我发送数据时出错了吗?

我发送请求的API是期望一个参数(下面的Java代码中我的方法中的"String Description")采用JSON的形式,并在下面 格式:

[
  {
    "ID": "-1",
    "Value": "value",
    "Desc": "description",
    "Group": "1"
  },
  {
    "Id": "-1",
    "Value": "value2",
    "Desc": "description2",
    "Group": "1"
  }
]

因此我将其作为JSON发送到下面的Java代码中。

=============================================== ================================= 我的错误(Apache Tomcat或Tombe登录Netbeans 8.0.1):

02-Oct-2014 09:24:38.787 SEVERE [http-apr-8080-exec-34] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [SendJSON_PUT] in context with path [/testapi] threw exception
 java.io.IOException: Server returned HTTP response code: 400 for URL:http://myapichecking.mydomain.com/webservice/groupcheck
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1838)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1439)
    at SendJSON_PUT.sendHttpRequest(SendJSON_PUT.java:157) // I have mentioned about line 157,103 & 71 in the code below
    at SendJSON_PUT.ContactUpdate(SendJSON_PUT.java:103)
    at SendJSON_PUT.doGet(SendJSON_PUT.java:71)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:618)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:725)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:291)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:239)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:136)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
    at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:526)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1078)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:655)
    at org.apache.coyote.http11.Http11AprProtocol$Http11ConnectionHandler.process(Http11AprProtocol.java:277)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.doRun(AprEndpoint.java:2381)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:2370)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

=============================================== ================================= 我的JAVA计划:

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.crypto.Mac;
import org.apache.commons.codec.binary.Hex;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;


@WebServlet("/SendJSON_PUT")
public class SendJSON_PUT extends HttpServlet {
  public SendJSON_PUT() {
  super();
   }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      response.setContentType("text/html;charset=UTF-8");
      PrintWriter out = response.getWriter();
      try {
           out.println("<!DOCTYPE html>");  // HTML 5
           out.println("<html><head>");
           out.println("<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>");
           // THE BELOW LINE IS LINE # 71
           out.println(new Gson().toJson(ContactUpdate("The Input Description Parameter Description","{\"ID\":\"123\",\"preferenceValue\":\"Check Description !\",\"Desc\":\"Update Description for 123\",\"Group\":\"1\"}")).replace("\\","")); 
           out.println("<head><title>Description PUT</title></head>");
           out.println("<body>");
           out.println("</body></html>");
        }   
        finally {
            out.close();  // Always close the output writer
        }
    }
    public static Object ContactUpdate(String APIDescription,String Description) throws IOException {
        String accessKey = "myaccesskey";
        String secretKey = "myprivatekey";
        String uRLCppList = "http://myapichecking.mydomain.com/webservice/groupcheck";
        String method = "PUT";
        java.util.Date currentTime = new java.util.Date();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
        String dateTimeString = sdf.format(currentTime);
        String signature = generateSignature(method, secretKey, dateTimeString);
        String authorization = accessKey + ":" + signature;
        Map<String, String> params = new HashMap<String, String>();
        params.put("For Description parameter", APIDescription);
        params.put("The Description", Description);
        // THIS BELOW LINE IS LINE #103
        String[] result = sendHttpRequest(uRLCppList, "POST", params, dateTimeString, authorization); 
         return result;
    }
    public static String[] sendHttpRequest(String requestUrl, String method, Map<String, String> params, String dateTimeString, String authorization) throws IOException {
        List<String> response = new ArrayList<String>();
        StringBuffer requestParams = new StringBuffer();
        if (params != null && params.size() > 0) {
            Iterator<String> paramIterator = params.keySet().iterator();
            while (paramIterator.hasNext()) {
                String key = paramIterator.next();
                String value = params.get(key);
                requestParams.append(URLEncoder.encode(key, "UTF-8"));
                requestParams.append("=").append(URLEncoder.encode(value, "UTF-8"));
                requestParams.append("&");
            }
        }
        URL url = new URL(requestUrl);
        URLConnection urlConn = url.openConnection();
        urlConn.setRequestProperty("accept", "application/json");
        urlConn.setRequestProperty("datetime", dateTimeString);
        urlConn.setRequestProperty("authorization", authorization);
        urlConn.setUseCaches(false);
        // the request will return a response
        urlConn.setDoInput(true);
        if ("POST".equals(method)) {
            // set request method to POST
            urlConn.setDoOutput(true);
        } else {
            // set request method to GET
            urlConn.setDoOutput(false);
        }
        if ("POST".equals(method) && params != null && params.size() > 0) {
            OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
            writer.write(requestParams.toString());
            writer.flush();  
        }
        //else {
        //if ("PUT".equals(method) && params != null && params.size() > 0) {
          //  OutputStreamWriter writer = new OutputStreamWriter(urlConn.getOutputStream());
           // writer.write(requestParams.toString());
            //writer.flush();  
        //}
        //}
        // reads response, store line by line in an array of Strings
        // // THIS BELOW LINE IS LINE # 157
        BufferedReader reader = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); 
        String line = "";
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        return (String[]) response.toArray(new String[0]);
    }
    public static String generateSignature(String method, String secretKey, String dateTimeString) {        
        String cs = String.format("%s\n\n\n%s\n\n\n", method, dateTimeString);
        String signature = createSignature(cs, secretKey);
        return  signature;
    }
    public static String createSignature(String stringIn, String scretKey) {
        String fixedData = stringIn.replace('\n', (char)10);
        // Calculate the hash of the information
        String digest = hmacSha1(scretKey, fixedData);
        return digest;
    } 
    public static String hmacSha1(String key, String value) {
        try {
            // Get an hmac_sha1 key from the raw key bytes
            byte[] keyBytes = key.getBytes("iso-8859-1");           
            SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

            // Get an hmac_sha1 Mac instance and initialize with the signing key
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(signingKey);

            // Compute the hmac on input data bytes
            byte[] rawHmac = mac.doFinal(value.getBytes("iso-8859-1"));

            //  Covert array of Hex bytes to a String
            return Base64.encode(rawHmac);

            //return new String(hexBytes, "UTF-8");
        } 
        catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

由于

0 个答案:

没有答案