我ThreadSafeClientConnManager在我的应用程序中使用了一些其他类,如HttpStatus,SSLSocketFactory,PlainSocketFactory,SchemeRegistry等.但是从API 22开始,它们都被标记为已弃用,并且我没有看到任何明确指示替换的内容他们.文档jas说"请使用openConnection().请访问此网页以获取更多详细信息",这并不能说清楚该怎么做.openConnection()只是指向URL类,而网页链接是从2011年开始讨论Apache类和之间的差异HttpUtrlConnection.那么,这是否意味着HttpUrlConnection从现在开始我们应该是useign 类?如果是这种情况,我认为它不是线程安全的(这就是我使用它的原因ThreadSafeClientConnManager).
有人可以帮我澄清一下吗?
我的目标是从Android 4.0使用REST Web服务HttpsURLConnection.除非我尝试POST某种方法,否则这种方法很好 这是相关的代码部分:
connection.setDoOutput(true);
connection.setChunkedStreamingMode(0);
ByteArrayOutputStream out = new ByteArrayOutputStream();
serializeObjectToStream(out, object);
byte[] array = out.toByteArray();
connection.getOutputStream().write(array, 0, array.length);
Run Code Online (Sandbox Code Playgroud)
这会引发以下异常:
java.net.HttpRetryException: Cannot retry streamed HTTP body
Run Code Online (Sandbox Code Playgroud)
从调试中我意识到我得到的输出流connection.getOuputStream()是类型的,ChunkedOutputStream并且从挖掘Androids源代码中我认为如果需要重试请求(无论出于何种原因),它会引发上述异常,因为它会发现它是不是用RetryableOutputStream它想在那里.
现在的问题是:如何使我的HttpsURLConnection返回这样的RetryableOutputStream,或者更确切地说,如何正确地阻止分块请求编码?我以为我已经这样做了setChunkedStreamingMode(0),但显然事实并非如此......
[编辑]
不,执行java.net.HTTPUrlConnection忽略0或更低的流模式:
public void setChunkedStreamingMode(int chunkLength) {
[...]
if (chunkLength <= 0) {
this.chunkLength = HttpEngine.DEFAULT_CHUNK_LENGTH;
} else {
this.chunkLength = chunkLength;
}
}
Run Code Online (Sandbox Code Playgroud) 为了将二进制文件上传到URL,我建议使用本指南.但是,该文件不在目录中,而是存储在MySql db中的BLOB字段中.BLOB字段byte[]在JPA中映射为属性:
byte[] binaryFile;
Run Code Online (Sandbox Code Playgroud)
我稍微修改了从指南中获取的代码,这样:
HttpURLConnection connection = (HttpURLConnection ) new URL(url).openConnection();
// set some connection properties
OutputStream output = connection.getOutputStream();
PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, CHARSET), true);
// set some headers with writer
InputStream file = new ByteArrayInputStream(myEntity.getBinaryFile());
System.out.println("Size: " + file.available());
try {
byte[] buffer = new byte[4096];
int length;
while ((length = file.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
output.flush();
writer.append(CRLF).flush();
writer.append("--" + boundary + "--").append(CRLF).flush();
}
// catch and close …Run Code Online (Sandbox Code Playgroud) 我想访问一个SOAP webservice url,其中https托管在远程虚拟机中.我在使用HttpURLConnection访问它时遇到异常.
这是我的代码:
import javax.net.ssl.*;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
/**
* Created by prasantabiswas on 07/03/17.
*/
public class Main
{
public static void main(String [] args)
{
try
{
URL url = new URL("https://myhost:8913/myservice/service?wsdl");
HttpURLConnection http = null;
if (url.getProtocol().toLowerCase().equals("https")) {
trustAllHosts();
HttpsURLConnection https = (HttpsURLConnection) url.openConnection();
https.setHostnameVerifier(DO_NOT_VERIFY);
http = https;
} else {
http = (HttpURLConnection) url.openConnection();
}
String SOAPAction="";
// http.setRequestProperty("Content-Length", String.valueOf(b.length));
http.setRequestProperty("Content-Type", "text/xml; charset=utf-8");
http.setRequestProperty("SOAPAction", SOAPAction);
http.setRequestMethod("GET");
http.setDoOutput(true);
http.setDoInput(true); …Run Code Online (Sandbox Code Playgroud) 我正在尝试向媒体类型设置为的jaxrs服务执行请求multipart/form-data.此请求包含实体列表(xml)和图像(png,二进制).我已经创建了BalusC 在此主题中描述的请求.
在wireshark中检查它之后,请求似乎没问题,除了ip头校验和错误.(说"可能是由IP校验和卸载引起的".)
这里我的大问题是如何在服务端处理多部分请求.我不希望包含来自apache.cxf,resteasy或任何类型的任何库.我想要依赖的是jaxrs api.
这两部分的要求有名字deliveries和signature,其中签名是发送二进制PNG图像文件.应该从xml解析交付列表(实体具有xmlrootelement注释等,因此这部分单独工作).我尝试用这种方式阅读不同的部分,但这真的是一个长期的结果;
@PUT
@Path("signOff")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void signOffDeliveries(@FormParam("deliveries") List<Delivery> deliveries, @FormParam("signature")File signature) {
//do something with the signature(image) and the list of deliveries.
}
Run Code Online (Sandbox Code Playgroud)
这当然不起作用,如果我在Websphere上运行请求,它会给我一个404 http状态代码,当我向嵌入式openejb(在我们的集成测试框架中)运行请求时,它会给我一个415.如果我删除FormParam注释,请求成功.
如何仅使用jaxrs api读取多部分请求的不同部分?
编辑
好了,所以我把它编织PUT到了POST,并@Encoding为params 添加了一个注释:
@POST
@Path("signOff")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public void signOffDeliveries(
@Encoded @FormParam("deliveries") String deliveries,
@Encoded @FormParam("signature") File signature) {
}
Run Code Online (Sandbox Code Playgroud)
现在我将xml作为文本字符串,但我无法自动将其解组为交付列表,即使Content-Type有效负载的这部分设置为application/xml.另一个问题是我收到的文件长度== 0,我无法从中读取任何字节.
我在这里错过了一个基本点吗?
我使用两种方法尝试使用HTTPS URL:
具有正确值的旧的已弃用和返回响应.
这是代码,它不需要忽略ssl证书它自己忽略它或可能使用其他技术:
public String newApiPost(String url,String p1,String p2,String p3){
HttpClient httpClient = new DefaultHttpClient();
// replace with your url
HttpPost httpPost = new HttpPost(url);
//Post Data
List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>
();
nameValuePair.add(new BasicNameValuePair("cliend_id",p1));
nameValuePair.add(new BasicNameValuePair("client_secret", p2));
nameValuePair.add(new BasicNameValuePair("key",p3));
//Encoding POST data
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// log exception
e.printStackTrace();
}
//making POST request.
try {
HttpResponse response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
String result = EntityUtils.toString(httpEntity,
HTTP.UTF_8);
Log.d("response", result);
// write …Run Code Online (Sandbox Code Playgroud) 我正在编写一个连接到网站并从中读取一行的应用程序.我是这样做的:
try{
URLConnection connection = new URL("www.example.com").openConnection();
BufferedReader rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = rd.readLine();
rd.close();
}catch (Exception e) {
//exception handling
}
Run Code Online (Sandbox Code Playgroud)
好吗?我的意思是,我在最后一行关闭了BufferedReader,但我没有关闭InputStreamReader.我应该从connection.getInputStream创建一个独立的InputStreamReader,还是从独立的InputStreamReader创建一个BufferedReader,而不是关闭所有两个读者?我认为最好将结束方法放在finally块中,如下所示:
InputStreamReader isr = null;
BufferedReader br = null;
try{
URLConnection connection = new URL("www.example.com").openConnection();
isr = new InputStreamReader(connection.getInputStream());
br = new BufferedReader(isr);
String response = br.readLine();
}catch (Exception e) {
//exception handling
}finally{
br.close();
isr.close();
}
Run Code Online (Sandbox Code Playgroud)
但它很难看,因为关闭方法可以抛出异常,所以我必须处理或抛出它.
哪种解决方案更好?或者什么是最好的解决方案?
我得到了java.lang.IllegalStateException:
java.lang.IllegalStateException:setRequestProperty调用方法
后,无法在连接建立后设置请求属性url.openConnection();
这是我正在尝试的:
URL url = new URL("https://49.205.102.182:7070/obsplatform/api/v1/mediadevices/545b801ce37e69cc");
urlConnection = (HttpsURLConnection) url
.openConnection();
urlConnection.setRequestProperty("Content-Type","application/json");
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?提前致谢.
大家好我正在编写一个简单的网页抓取脚本,需要连接到网页,自动跟踪302重定向,给我链接的最终网址,让我抓住HTML.
做这些事情的首选java lib是什么?
谢谢
我使用HttpURLConnection来做HTTP POST,但我总是得不到完整的响应.我想调试这个问题,但是当我逐步完成它的工作时.我认为这一定是一个时间问题,所以我添加了Thread.sleep,它确实使我的代码工作,但这只是一个临时的解决方法.我想知道为什么会发生这种情况以及如何解决.这是我的代码:
public static InputStream doPOST(String input, String inputMimeType, String url, Map<String, String> httpHeaders, String expectedMimeType) throws MalformedURLException, IOException {
URL u = new URL(url);
URLConnection c = u.openConnection();
InputStream in = null;
String mediaType = null;
if (c instanceof HttpURLConnection) {
//c.setConnectTimeout(1000000);
//c.setReadTimeout(1000000);
HttpURLConnection h = (HttpURLConnection)c;
h.setRequestMethod("POST");
//h.setChunkedStreamingMode(-1);
setAccept(h, expectedMimeType);
h.setRequestProperty("Content-Type", inputMimeType);
for(String key: httpHeaders.keySet()) {
h.setRequestProperty(key, httpHeaders.get(key));
if (logger.isDebugEnabled()) {
logger.debug("Request property key : " + key + " / value : " + httpHeaders.get(key));
}
} …Run Code Online (Sandbox Code Playgroud)