我正在构建一个与使用基本身份验证的REST接口对话的Eclipse插件.当身份验证失败时,我想弹出我的插件的设置对话框并重试.通常我可以使用静态Authenticator.setDefault()为所有人设置一个身份验证器HttpURLConnection,但是因为我正在编写一个插件,所以我不想覆盖Eclipse的默认值Authenticator(org.eclipse.ui.internal.net.auth);
我想Authenticator在加载之前设置我的自定义并在之后放回Eclipse的默认值,但我想这将导致多线程的种类问题,所以我很快就失去了这个概念.
Google搜索会产生各种结果,基本上告诉我这是不可能的:
Java URLConnection API应该有一个setAuthenticator(Authenticator)方法,以便在需要身份验证的多线程上下文中更容易地使用此类.
如果应用程序包含很少的第三方插件,并且每个插件都使用自己的Authenticator,我们应该做什么?每次调用"Authenticator.setDefault()"方法都会重写以前定义的Authenticator ...
是否有任何不同的方法可以帮助我克服这个问题?
(已解决 - 见下面的评论)
我有一个实现多部分文件上传的类.代码适用于我尝试过的每个java客户端,除了Android,它是我的Android应用程序中唯一不能与我的后端服务配合使用的HTTP请求代码.
连接responseCode是"-1"所以这里有一些非常讨厌的东西.在Apache访问或错误日志中没有显示任何条目,似乎请求永远不会脱离Android平台.代码通过连接写入正确,但挂起连接读取,超时然后返回.真实手机和模拟器的行为是相同的.
有没有人知道在Android中发布多部分文件时需要注意的任何问题?
我包括下面的课程(制作的小卫生模型),所以你可以看到我在做什么
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class GeoPictureUploader
{
static String serviceDomain = "http://staging.abaqus.net";
static String postUrl = serviceDomain + "/geo/upl/wupload/pictures";
static String CRLF = "\r\n";
static String twoHyphens = "--";
static String boundary = "*****mgd*****";
private String pictureFileName = null;
private String name = null;
private String password = null;
private DataOutputStream dataStream = null;
enum ReturnCode …Run Code Online (Sandbox Code Playgroud) 是否可以获取使用HttpURLConnection下载的文件的名称?
URL url = new URL("http://somesite/getFile?id=12345");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setAllowUserInteraction(false);
conn.setDoInput(true);
conn.setDoOutput(true);
conn.connect();
InputStream is = conn.getInputStream();
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,我无法从URL中提取文件名,但服务器将以某种方式向我发送文件名.
我正在编写一个连接到servlet的程序,感谢a HttpURLConnection但是我在查看url时卡住了
public void connect (String method) throws Exception {
server = (HttpURLConnection) url.openConnection ();
server.setDoInput (true);
server.setDoOutput (true);
server.setUseCaches (false);
server.setRequestMethod (method);
server.setRequestProperty ("Content-Type", "application / xml");
server.connect ();
/*if (server.getResponseCode () == 200)
{
System.out.println ("Connection OK at the url:" + url);
System.out.println ("------------------------------------------- ------- ");
}
else
System.out.println ("Connection failed");
}*/
Run Code Online (Sandbox Code Playgroud)
我收到了错误:
java.net.ProtocolException:读取输入后无法写入输出.
如果我用注释中的代码检查网址,但不幸的是它完美地工作,我需要检查网址,所以我认为问题来自getResponseCode方法,但我不知道如何解决它
非常感谢你
对于PUT,我在HttpURLConnection中设置内容的长度.
urlConnection.setRequestProperty("Content-Length", "" + responseJSONArray.toString(2).getBytes("UTF8").length);
Run Code Online (Sandbox Code Playgroud)
实际的字节数是74.但是,当我查询urlConnection我返回的内容长度时-1.这是为什么?为什么长度不相等(假设我设定了这个)?
我必须设置内容长度,因为我收到了411服务器的响应.
(另外,在Sun的例子中,我看到第二个参数setRequestProperty是类型int而不是String,这看起来很奇怪.)
我看不出这段代码有什么问题:
JSONObject msg; //passed in as a parameter to this method
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setDoInput(true);
httpCon.setUseCaches(false);
httpCon.setRequestProperty( "Content-Type", "application/json" );
httpCon.setRequestProperty("Accept", "application/json");
httpCon.setRequestMethod("POST");
OutputStream os = httpCon.getOutputStream();
OutputStreamWriter osw = new OutputStreamWriter(os, "UTF-8");
msg.write(osw);
osw.flush();
osw.close();
os.close(); //probably overkill
Run Code Online (Sandbox Code Playgroud)
在服务器上,我根本没有发布帖子内容,零长度字符串.
到目前为止,我已经使用以下代码片段来发送和接收JSON字符串:
static private String sendJson(String json,String url){
HttpClient httpClient = new DefaultHttpClient();
String responseString = "";
try {
HttpPost request = new HttpPost(url);
StringEntity params =new StringEntity(json, "UTF-8");
request.addHeader("content-type", "application/json");
request.setEntity(params);
HttpResponse response = httpClient.execute(request);
HttpEntity entity = response.getEntity();
responseString = EntityUtils.toString(entity, "UTF-8");
}catch (Exception ex) {
ex.printStackTrace();
// handle exception here
} finally {
httpClient.getConnectionManager().shutdown();
}
return responseString;
}
Run Code Online (Sandbox Code Playgroud)
即使json字符串包含UTF-8字符,上面的代码工作也很完美,一切正常.
出于几个原因,我不得不改变发送HTTP post请求的方式,并使用HttpURLConnection代替apache的HttpClient.这是我的代码:
static private String sendJson(String json,String url){
String responseString = "";
try {
URL m_url = new URL(url); …Run Code Online (Sandbox Code Playgroud) 当我将DoOutput设置为true时,我收到非法状态异常.
public boolean sendLinksToMaster(String ipport, List<String> links){
boolean sent = false;
String[] tokens = ipport.split(":");
String data = edu.cis555.searchengine.utils.Utils.generateLinks(links);
HttpURLConnection conn=null;
try{
String encodedData = URLEncoder.encode(data, "UTF-8");
try{
String ip =tokens[0];
String port = tokens[1];
String path = edu.cis555.searchengine.utils.Constants.URL_ADD_LINK;
System.setProperty("http.keepAlive", "false");
URL u = new URL("http", ip, Integer.parseInt(port),"/"+path);
conn = (HttpURLConnection)u.openConnection();
//ERROR IN THIS LINE
conn.setDoOutput(true);
conn.setRequestMethod("POST");
OutputStream stream = conn.getOutputStream();
stream.write(encodedData.getBytes());
stream.close();
if(conn.getResponseCode() == HttpURLConnection.HTTP_OK)
sent=true;
// LOG.debug(conn.getResponseCode());
conn.disconnect();
}catch(MalformedURLException mfe){
LOG.debug(mfe.getMessage());
if(conn!=null){
conn.disconnect();
}
}catch(IOException ioe){
LOG.debug(ioe.getMessage());
if(conn!=null){ …Run Code Online (Sandbox Code Playgroud) 通过请求标头发送数据和通过请求正文发送数据有什么区别.在什么情况下,我们必须通过标题/正文发送数据,何时不应该通过标题/正文发送数据?
javascript servlets httprequest httpurlconnection http-headers
我一直试图将代码弄清楚一段时间,但是没有成功.每次应用程序崩溃时都会抛出一些随机异常.
我从youtube上的教程中学到了这段代码,尽管如此,代码对我来说并不适用.
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.Buffer;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
Button b1;
TextView t1;
private Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.bthhit);
t1=(TextView)findViewById(R.id.tvJSONitem);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
}); …Run Code Online (Sandbox Code Playgroud) java ×7
android ×3
http ×3
json ×2
exception ×1
http-headers ×1
httprequest ×1
inputstream ×1
javascript ×1
post ×1
servlets ×1