java httppost 400_得到400响应httpurlconnection发送post请求

尝试将python代码转换为java代码以获得httppost请求,但始终得到400响应。尝试在我的电脑中使用与本地Web服务相同的代码,则不存在任何问题。请参阅Python代码:得到400响应httpurlconnection发送post请求

post_data = {'monitoredObjects':'VZLab-IViewG10-2','monitoredObjectType':'Probe'}

print(post_data)

postfields = urlencode(post_data)

response = BytesIO()

b = pycurl.Curl()

b.setopt(b.URL, base+"capture")

b.setopt(b.HTTPHEADER, ['username:'+username,'securitytoken:'+securitytoken])

b.setopt(b.SSL_VERIFYPEER, 0)

b.setopt(a.SSL_VERIFYHOST, 0)

b.setopt(b.WRITEDATA, response)

b.setopt(b.POST, 1)

b.setopt(b.POSTFIELDS, postfields)

b.perform()

b.close()

我的Java代码:

public void method(){

String securityToken = "12134";

HashMap header = new HashMap();

header.put("username", username);

header.put("password", password);

header.put("securitytoken", securityToken);

String api = "capture";

JsonObject parameters = new JsonObject();

parameters.addProperty("monitoredObjects", System.getProperty("monitoredObjects"));

parameters.addProperty("monitoredObjectType", System.getProperty("monitoredObjectType"));

String captureResult = executePost(baseUrl, api, header, parameters.toString(), "POST");

String captureid = Xml.getXPathValue(result, "//startCapture/isa:captureId/text()");

}

public static String executePost(String baseUrl, String api, HashMap header, String urlParameters, String httpMethod) {

HttpURLConnection connection = null;

try {

// Create connection

URL url = new URL(baseUrl + api);

connection = (HttpURLConnection) url.openConnection();

connection.setRequestMethod(httpMethod);

connection.setRequestProperty("Content-Type", "application/json");

connection.setRequestProperty("Content-Language", "en-US");

connection.setRequestProperty("username", (String) header.get("username"));

connection.setRequestProperty("securitytoken", (String) header.get("securitytoken"));

/*

* String userPassword = username + ":" + password; String encoding = new

* sun.misc.BASE64Encoder().encode(userPassword.getBytes()); connection.setRequestProperty("Authorization", "Basic " +

* encoding);

*/

// connection.setRequestProperty("Accept-Encoding", "gzip");

connection.setUseCaches(false);

connection.setDoOutput(true);

// Send request

if (urlParameters != null) {

String encodedString = URLEncoder.encode(urlParameters);

OutputStream wr = connection.getOutputStream();

BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(wr, "UTF-8"));

writer.write(encodedString);

writer.flush();

writer.close();

wr.close();

// wr.write(urlParameters.getBytes("UTF-8"));

// wr.close();

}

int responseCode = connection.getResponseCode();

logger.info("\nSending 'POST' request to URL : " + url);

logger.info("Post headers : " + header);

logger.info("Post parameters : " + urlParameters);

logger.info("Response Code : " + responseCode);

// Get Response

if (responseCode == 200) {

InputStream is = connection.getInputStream();

BufferedReader rd = new BufferedReader(new InputStreamReader(is));

StringBuilder response = new StringBuilder();

String line;

while ((line = rd.readLine()) != null) {

response.append(line);

response.append('\r');

}

rd.close();

logger.info("*** BEGIN ***");

logger.info(response.toString());

logger.info("*** END ***");

return response.toString();

}

return null;

} catch (Exception e) {

logger.error(e.getMessage());

return null;

} finally {

if (connection != null) {

connection.disconnect();

}

}

}

+0

400 HTTP响应是关于错误的请求,因此您的请求结构中可能有错误,那么请您提供更多信息,例如“baseUrl”的值是什么?如果你不能提供这些信息,你至少可以展示它的结构。 –

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我知道你的问题了。关于Java实现响应重定向并发送POST请求的操作示例,可以参考以下代码: ```java import java.net.HttpURLConnection; import java.net.URL; import java.io.OutputStream; import java.io.BufferedReader; import java.io.InputStreamReader; public class RedirectAndPost { public static void main(String[] args) throws Exception { String url = "http://www.example.com/redirect"; String postBody = "param1=value1&param2=value2"; HttpURLConnection connection = null; URL redirectUrl = new URL(url); while (true) { connection = (HttpURLConnection) redirectUrl.openConnection(); connection.setInstanceFollowRedirects(false); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connection.setRequestProperty("charset", "utf-8"); connection.setRequestProperty("Content-Length", Integer.toString(postBody.getBytes().length)); connection.setUseCaches(false); connection.setDoOutput(true); OutputStream outputStream = connection.getOutputStream(); outputStream.write(postBody.getBytes("UTF-8")); outputStream.flush(); outputStream.close(); int statusCode = connection.getResponseCode(); if (statusCode == HttpURLConnection.HTTP_MOVED_TEMP || statusCode == HttpURLConnection.HTTP_MOVED_PERM || statusCode == HttpURLConnection.HTTP_SEE_OTHER) { String redirectLocation = connection.getHeaderField("Location"); redirectUrl = new URL(redirectLocation); continue; } else { BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; StringBuilder responseBuilder = new StringBuilder(); while ((line = reader.readLine()) != null) { responseBuilder.append(line); } reader.close(); String response = responseBuilder.toString(); System.out.println(response); break; } } } } ``` 这个示例代码实现了向一个URL发送POST请求,并在接收到重定向响应时自动跟随重定向并重新发送POST请求。注意,我们在第一次请求时将`setInstanceFollowRedirects`方法设置为`false`,以便我们能够手动处理重定向响应。当我们接收到重定向响应时,从响应头中获取重定向URL,并将其存储在`redirectUrl`变量中,然后继续重新发送POST请求,直到我们接收到最终响应为止。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值