关于CloseableHttpClient 和 HttpURLConnection 中的 cookie问题

我在请求需要登录的链接时发生的问题。。。

1、**用CloseableHttpClient** 请求
返回:
{"error_no":102,"error_msg":"user not login","result":null}...

2、**用HttpURLConnection** 请求
返回:
resp >>> {"error_no":40004,"error_msg":"\u9886\u53d6\u5931\u...
说明已经登录了,是我想要的结果

同样的url,同样的cookie,为什么用CloseableHttpClient是未登录?

下面分别是两个请求方法的代码:
图片说明
图片说明

1个回答

CloseableHttpClient 的cookie应该设置在head?

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
其他相关推荐
关于java的HTTPURLConnection的使用原理

一直对于http协议的请求原理不是很明白,于是做了如下测试 用ServerSocket做了一个服务端,接收请求,并获取输入流打印, 用HTTPURLConnertion向服务端发送请求, 第一次测试时,客户端只使用了输出流,并使用了flush().然后再close,结果服务端什么都没有输出 就报错了 第二次测试,客户端,即使用了输出流,又使用了输入流,然后再close,结果服务端,正常输出了 , 于是迷茫了,到底时怎么回事啊,请问高手.

HttpURLConnection的字符流中文乱码

程序是UTF-8编码,我通过HttpURLConnection获得网页源代码 InputStream in = urlConnection.getInputStream(); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(in)); StringBuffer temp = new StringBuffer(); String line = bufferedReader.readLine(); while (line != null) { temp.append(line).append("\r\n"); line = bufferedReader.readLine(); } bufferedReader.close(); String txt = new String(temp.toString().getBytes(), "utf-8"); System.out.println(txt); 我在Eclipse的控制台中打印正常,在CMD下运行中文就乱码了,打包成jar运行也是乱码, 请问如何解决?

那httpurlConnection 和urlConnection相比 到底简化了什么 ?

url+socket=urlconnection吗 是不是httpurlConnection 的设置请求方法相比于UrlConnection简化了一些内容? 还有就是响应头 是不是我们不用管啊

HttpUrlConnection socks5 代理问题

代码如下: InetSocketAddress inetSocketAddress = new InetSocketAddress(proxyIp, 1080); Proxy proxy = new Proxy(Proxy.Type.SOCKS, inetSocketAddress); URL url = new URL("https://XXXX"); HttpURLConnection conn = (HttpURLConnection)url.openConnection(proxy); conn.setRequestMethod("POST"); 报错如下: java.net.SocketException: SOCKS : authentication failed at java.net.SocksSocketImpl.connect(Unknown Source) at java.net.Socket.connect(Unknown Source) at sun.net.NetworkClient.doConnect(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.openServer(Unknown Source) at sun.net.www.http.HttpClient.<init>(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.http.HttpClient.New(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source) at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source) 如何设置不需要用户密码验证。求大神!!!

关于HttpURLConnection 的问题

当使用https协议时,url.openConnection()返回的是:conn:com.android.okhttp.internal.http.HttpURLConnectionImpl 这是什么原因?

HttpURLConnection做通讯, get方式带中文参数通讯失败

android中用HttpURLConnection做通讯, get方式带中文参数,在 android5.0以下的手机通讯失败,在android5.0以上的手机通讯成功 代码如下 /** * Get请求,获得返回数据 * * @param urlStr * @return * @throws Exception */ public static String doGet(String urlStr) { URL url = null; HttpURLConnection conn = null; InputStream is = null; ByteArrayOutputStream baos = null; try { LogUtils.i("urlStr = ",urlStr); url = new URL(urlStr); LogUtils.i("url = ",url.toString()); conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(READ_TIMEOUT_MILLIONS); conn.setConnectTimeout(CONN_TIMEOUT_MILLIONS); conn.setRequestMethod("GET"); conn.setRequestProperty("accept", "*/*"); conn.setRequestProperty("connection", "Keep-Alive"); conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // conn.setRequestProperty("Accept-Charset", "UTF-8"); // conn.setRequestProperty("Accept-Language","zh-CN"); conn.setRequestProperty("charset", "utf-8"); conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded"); if (conn.getResponseCode() == 200) { is = conn.getInputStream(); baos = new ByteArrayOutputStream(); int len = -1; byte[] buf = new byte[1024]; while ((len = is.read(buf)) != -1) { baos.write(buf, 0, len); } baos.flush(); return baos.toString(); } else { // throw new RuntimeException(" responseCode is not 200 ... "); String msg = "獲取數據失敗,返回網絡代碼:" + conn.getResponseCode(); // String jsonstr = "{'status':'false';'msg':'"+msg+"'}"; String jsonstr = "{'errno': 0,'message':'" + msg + "'}"; return jsonstr; } } catch (Exception e) { // e.printStackTrace(); // return "網絡連接失敗或超時"; String msg = "網絡連接失敗或超時"; // String jsonstr ="{'status':'false';'msg':'"+msg+"'}"; String jsonstr = "{'errno': 0,'message':'" + msg + "'}"; return jsonstr; } finally { try { if (is != null) { is.close(); is = null; } } catch (IOException e) { } try { if (baos != null) { baos.close(); baos = null; } } catch (IOException e) { } conn.disconnect(); } // return null; }

android 关于HttpURLConnection 抛出了异常

``` private String url = "http://www.baidu.com"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_download); new Thread(new Runnable() { @Override public void run() { //从网络获取数据 String msgs = get(url); } }).start(); } public String get(String url) { HttpURLConnection conn = null; try { // 利用string url构建URL对象 URL mURL = new URL(url); conn = (HttpURLConnection) mURL.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(10000); conn.setConnectTimeout(10000); int responseCode = conn.getResponseCode(); String msg = getString(responseCode); Log.i("msg",msg); if (responseCode == 200) { InputStream is = conn.getInputStream(); String response = getStringFromInputStream(is); return response; } else { throw new NetworkErrorException("response status is "+responseCode); } } catch (Exception e) { e.printStackTrace(); } finally { if (conn != null) { conn.disconnect(); } } return null; } 代码如上,拿百度网址测试是没问题的,是可以到getInputStream的,也显示出responseCode是200 ; connected 也是true 拿自己服务器的url测试就出了问题,在执行getResponseCode时就会抛出异常![跳转抛出异常](https://img-ask.csdn.net/upload/201605/29/1464464089_453718.png),但是connected情况是true的![](https://img-ask.csdn.net/upload/201605/29/1464464132_966673.png) 这个错误是因为什么呢``` ```

HttpURLConnection 带 cookie 请求 ?

url = "http://www.baidu.com"; URL realUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection)realUrl.openConnection(); String cookieval = conn.getHeaderField("set-cookie"); String sessionid = null; if(cookieval != null){ sessionid = cookieval.substring(0, cookieval.indexOf(";")); conn.addRequestProperty("Cookie", sessionid); } conn.setRequestProperty("Accept","text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"); conn.setRequestProperty("Accept-Encoding","gzip, deflate, sdch"); conn.setRequestProperty("Accept-Language","zh-CN,zh;q=0.8"); conn.setRequestProperty("Cache-Control","max-age=0"); conn.setRequestProperty("Connection","keep-alive"); conn.setRequestProperty("Upgrade-Insecure-Requests","1"); conn.setRequestProperty("Cookie",sessionid); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"); conn.connect(); int code = conn.getResponseCode(); 这样抛异常:Exception in thread "main" java.lang.IllegalStateException: Already connected at sun.net.www.protocol.http.HttpURLConnection.addRequestProperty(HttpURLConnection.java:2256) at com.huruxi.practice.http.HttpURLTest.getWebData(HttpURLTest.java:26) at com.huruxi.practice.http.HttpURLTest.main(HttpURLTest.java:87) 通过HttpURLConnection 访问网站,网站需要带cookie,我这样先获取,在设置cookie有异常,如果在浏览器中访问网站拷贝cookie来执行是可以的 技术较弱,大牛海涵,

java HttpURLConnection 模拟 返回和预计的不一样

访问的地址是:http://aq.qq.com/cn2/login_limit/login_limit_index public final static String CONTENT_TYPE = "Content-Type"; public static void main(String[] args) throws Exception { // login // 验证码的位置 // Content content = getRandom("GET", // "http://localhost:8080/back/random.action", null, null, false,"d:/"); Content content = getRandom( "GET", "http://captcha.qq.com/getimage?aid=2001601&0.6973676234483719", null, null, false, "d:/"); // build request headers & do rate of user review List<String> lsit = content.getHeaders().get("Set-Cookie"); Map<String, String> resmap = new HashMap<String, String>(); String cookie = ""; if (lsit != null) { StringBuffer sb = new StringBuffer(); boolean isLast = false; int i = 0; for (String val : lsit) { i++; if (i == lsit.size()) { isLast = true; } int pos = val.indexOf("="); if (pos != -1) { String cookieName = val.substring(0, pos); String cookieVal = val.substring(pos + 1); System.out.println(cookieName + ":" + cookieVal); cookieVal = cookieVal.split(";")[0]; if (isLast) { sb.append(cookieName + "=" + cookieVal); } else { sb.append(cookieName + "=" + cookieVal + ";"); } } } cookie = sb.toString(); } String a = ""; System.out.print("请输入验证码:"); BufferedReader strin = new BufferedReader(new InputStreamReader( System.in)); try { a = strin.readLine(); } catch (IOException e) { e.printStackTrace(); } System.out.println("输入的数是:" + a); String userCode = "admin"; String account = "1158752036"; // String loginUrl = "http://localhost:9090/w/login.action"; String rateReviewUrl = "http://aq.qq.com/cn2/ajax/check_verifycode?verify_code=" + URLEncoder.encode(a, "utf-8") + "&account=" + URLEncoder.encode(account, "utf-8") + "&session_type=" + URLEncoder.encode("on_rand", "utf-8"); // String rateReviewUrl = // "http://fdjkpoi.xicp.net/udp/baseinfo/getQQ.action"; Map<String, String> paramMap = new HashMap<String, String>(); // content = curl("POST", loginUrl, paramMap, resmap, false, ""); System.out .println("第一次 content.getBody()= " + content == null ? "no body" : content.getBody()); // build request headers & do rate of user review // paramMap = new HashMap<String, String>(); content = curl("get", rateReviewUrl, paramMap, cookie, false, ""); // inFile(content.getBody(), "D:/sss.txt"); } public static Content curl(String method, // 方法类型 String sUrl,// 要解析的URL Map<String, String> paramMap, // 存放用户名和密码的map String requestHeaderMap,// 存放COOKIE的map boolean isOnlyReturnHeader, String path) throws Exception {// 存放文件路径 System.out.println("-------------" + sUrl + "-------------------"); Content content = null; try { URL getUrl = new URL(sUrl); // 根据拼凑的URL,打开连接,URL.openConnection函数会根据URL的类型, // 返回不同的URLConnection子类的对象,这里URL是一个http,因此实际返回的是HttpURLConnection HttpURLConnection connection = (HttpURLConnection) getUrl .openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Accept", "application/json, text/javascript, */*"); connection.setRequestProperty("Accept-Encoding", "UTF-8"); connection.setRequestProperty("Connection", "keep-alive"); connection.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); connection.setRequestProperty("Cookie", requestHeaderMap); // 进行连接,但是实际上get request要在下一句的connection.getInputStream()函数中才会真正发到 // 服务器 connection.connect(); // 取得输入流,并使用Reader读取 BufferedReader reader = new BufferedReader(new InputStreamReader( connection.getInputStream(),"UTF-8")); String lines; while ((lines = reader.readLine()) != null) { System.out.println(lines); } reader.close(); // 断开连接 connection.disconnect(); } catch (Exception e) { return null; } finally { } return content; } public static Content getRandom(String method, String sUrl,// 要解析的url Map<String, String> paramMap, // 存放用户名和密码的map Map<String, String> requestHeaderMap,// 存放COOKIE的map boolean isOnlyReturnHeader, String path) { Content content = null; HttpURLConnection httpUrlConnection = null; InputStream in = null; try { URL url = new URL(sUrl); boolean isPost = "POST".equals(method); if (method == null || (!"GET".equalsIgnoreCase(method) && !"POST" .equalsIgnoreCase(method))) { method = "POST"; } URL resolvedURL = url; URLConnection urlConnection = resolvedURL.openConnection(); httpUrlConnection = (HttpURLConnection) urlConnection; httpUrlConnection.setRequestMethod(method); httpUrlConnection.setRequestProperty("Accept-Language", "zh-cn,zh;q=0.5"); // Do not follow redirects, We will handle redirects ourself httpUrlConnection.setInstanceFollowRedirects(false); httpUrlConnection.setDoOutput(true); httpUrlConnection.setDoInput(true); httpUrlConnection.setConnectTimeout(5000); httpUrlConnection.setReadTimeout(5000); httpUrlConnection.setUseCaches(false); httpUrlConnection.setDefaultUseCaches(false); httpUrlConnection.connect(); int responseCode = httpUrlConnection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK || responseCode == HttpURLConnection.HTTP_CREATED) { byte[] bytes = new byte[0]; if (!isOnlyReturnHeader) { DataInputStream ins = new DataInputStream(httpUrlConnection .getInputStream()); // 验证码的位置 DataOutputStream out = new DataOutputStream( new FileOutputStream(path + "/code.bmp")); byte[] buffer = new byte[4096]; int count = 0; while ((count = ins.read(buffer)) > 0) { out.write(buffer, 0, count); } out.close(); ins.close(); } String encoding = null; if (encoding == null) { encoding = getEncodingFromContentType(httpUrlConnection .getHeaderField(CONTENT_TYPE)); } content = new Content(sUrl, new String(bytes, encoding), httpUrlConnection.getHeaderFields()); } } catch (Exception e) { return null; } finally { if (httpUrlConnection != null) { httpUrlConnection.disconnect(); } } return content; } public static String getEncodingFromContentType(String contentType) { String encoding = null; if (contentType == null) { return null; } StringTokenizer tok = new StringTokenizer(contentType, ";"); if (tok.hasMoreTokens()) { tok.nextToken(); while (tok.hasMoreTokens()) { String assignment = tok.nextToken().trim(); int eqIdx = assignment.indexOf('='); if (eqIdx != -1) { String varName = assignment.substring(0, eqIdx).trim(); if ("charset".equalsIgnoreCase(varName)) { String varValue = assignment.substring(eqIdx + 1) .trim(); if (varValue.startsWith("\"") && varValue.endsWith("\"")) { // substring works on indices varValue = varValue.substring(1, varValue.length() - 1); } if (Charset.isSupported(varValue)) { encoding = varValue; } } } } } if (encoding == null) { return "UTF-8"; } return encoding; } // 这个是输出 public static boolean inFile(String content, String path) { PrintWriter out = null; File file = new File(path); try { if (!file.exists()) { file.createNewFile(); } out = new PrintWriter(new FileWriter(file)); out.write(content); out.flush(); return true; } catch (Exception e) { e.printStackTrace(); } finally { out.close(); } return false; } public static String getHtmlReadLine(String httpurl) { String CurrentLine = ""; String TotalString = ""; InputStream urlStream; String content = ""; try { URL url = new URL(httpurl); HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.connect(); System.out.println(connection.getResponseCode()); urlStream = connection.getInputStream(); BufferedReader reader = new BufferedReader( new InputStreamReader(urlStream, "utf-8")); while ((CurrentLine = reader.readLine()) != null) { TotalString += CurrentLine + "\n"; } content = TotalString; } catch (Exception e) { } return content; } } class Content { private String url; private String body; private Map<String, List<String>> m_mHeaders = new HashMap<String, List<String>>(); public Content(String url, String body, Map<String, List<String>> headers) { this.url = url; this.body = body; this.m_mHeaders = headers; } public String getUrl() { return url; } public String getBody() { return body; } public Map<String, List<String>> getHeaders() { return m_mHeaders; } 贴上代码, 1158752036 QQ号已经被冻结,但是返回是 {"Err":"0" } 我输入没有冻结的QQ号 返回的也一样,输入错误的验证码,返回是 {"Err":"您输入的验证码有误" },证明已经通了,不知是否这个地址 还有其他的参数吗? 小白一个往大神教导

关于使用HttpURLConnection下载大文件的一些问题 求大神指导

下面是我的函数 private void getFile() { new Thread(new Runnable() { @Override public void run() { synchronized (this) { URL url = null; InputStream inputStream = null; FileOutputStream outputStream = null; long fileSize = 0; try { url = new URL(downloadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(28000); connection.setRequestMethod("GET"); if (connection.getResponseCode() == 200) { inputStream = connection.getInputStream(); File file = new File(Environment.getExternalStorageDirectory() + "/" + directoriy, filename); outputStream = new FileOutputStream(file); fileSize = connection.getContentLength(); int length = 0; byte[] buffer = new byte[1024]; int downloadSize = 0; while ((length = inputStream.read(buffer)) != -1) { downloadSize = downloadSize + length; progress[0] = downloadSize / (float) fileSize; outputStream.write(buffer, 0, length); handler.sendEmptyMessage(INVALIDATE1); } outputStream.flush(); outputStream.close(); handler.sendEmptyMessage(LOAD_SUCCESS1); } } catch (MalformedURLException e) { handler.sendEmptyMessage(LOAD_ERROR1); e.printStackTrace(); e.getMessage(); try { if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } catch (IOException e) { handler.sendEmptyMessage(LOAD_ERROR1); e.printStackTrace(); if (inputStream != null) try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } if (outputStream != null) try { outputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }).start(); } 用上面的函数下载一个1个G的文件要改成POST方式吗?需要的话函数需要拿些改动呢,还有就是下载启动大文件之后对UI有很大的影响,列表直接卡住了,想请问用什么方法可以优化一下呢?

Android开发中的HttpURLConnection的问题

为什么我连接不到服务器求大神告知谢谢。我的代码如下 String n = name.getText().toString(); String p = password.getText().toString(); URL url = new URL("http://192.168.211.19:8080/AndroidTest/Login?name=" + n + "&password" + p); HttpURLConnection uc = (HttpURLConnection) url.openConnection(); InputStream out = uc.getInputStream(); String result = String.valueOf(out.read()); 服务器端代码如下 String name = request.getParameter("name"); String password = request.getParameter("password"); System.out.println(name + password); ServletOutputStream out = response.getOutputStream(); if(name != null && password != null && name.equals("admin")){ out.print("1"); }else{ out.print("0"); }在线等挺急的

HttpURLConnection只有localhost中的原始数据

<div class="post-text" itemprop="text"> <p>The java code insert raw data into test.php, but it only works with localhost url, and don't with public ip</p> <p>My urls,</p> <pre><code>//this URL work perfect, output: {"a":"b"} phpOK postJSON("http://192.168.1.100/test.php?username=user&amp;password=pass"); //this URL don't work, output: phpOK postJSON("http://myddns.net/test.php?username=user&amp;password=pass"); </code></pre> <p>Code to send data,</p> <pre><code>public String postJSON(String URL, String jsonStr) { StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); StrictMode.setThreadPolicy(policy); HttpURLConnection urlConnection = null; StringBuffer response = null; try { URL url = new URL(URL); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestProperty("Content-Type", "application/json"); urlConnection.setRequestMethod("POST"); urlConnection.setFixedLengthStreamingMode(jsonStr.getBytes().length); urlConnection.setConnectTimeout(5000); urlConnection.setReadTimeout(5000); urlConnection.setUseCaches(false); urlConnection.setDoOutput(true); urlConnection.setDoInput(true); urlConnection.connect(); JSONObject jsonStr= new JSONObject(); jsonStr.put("a", "b"); DataOutputStream printout = new DataOutputStream(urlConnection.getOutputStream()); printout.writeBytes(jsonStr); printout.flush(); printout.close(); //if(urlConnection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream is = urlConnection.getInputStream(); BufferedReader br = new BufferedReader(new InputStreamReader(is)); String inputLine; response = new StringBuffer(); while ((inputLine = br.readLine()) != null) { response.append(inputLine); } br.close(); } finally { if(urlConnection != null) urlConnection.disconnect(); if(response != null) return response.toString(); else return ""; } } </code></pre> <p>My PHP,</p> <pre><code>//in test.php &lt;?php $phpInput = file_get_contents('php://input'); echo $phpInput." phpOK"; if(isset($_GET['username']) &amp; isset($_GET['password'])) echo "extra vars catched" ?&gt; </code></pre> <p>I test in a real phone using 3G data and... My server is blocking in some way the public ip, because when I use the local ip it's work perfect. Blocking the writing output stream: urlConnection.getOutputStream() </p> </div>

HttpURLConnection 怎么接收数组?

在myEclipse中,通过 HttpServletResponse的getWriter()获得了PrintWriter,然后通过PrintWriter的print( )方法传递了一个二维数组。请问各位,怎么在 HttpURLConnection中接收呢?或者说通过getInputStream()接收后怎么转换成二位数组?拜托各位!

HttpURLConnection中setFollowRedirects()的问题

使用HttpURLConnection请求时设置了setFollowRedirects()为false,为什么还是会重定向?检查getFollowRedirects()的返回结果为false,但请求确实发生了重定向。求大神解释一下。

在HttpURLConnection中为什么JSONObject不作为Params工作但String作为Params工作

<div class="post-text" itemprop="text"> <p>I am using HttpUrlConnection to post some data to my server here is the function: </p> <pre><code>private String register(String myurl) throws IOException { String resp = null; try { JSONObject parameters = new JSONObject(); // parameters.put("jsonArray", ((makeJSON()))); parameters.put("key", "key");//getencryptkey()); URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); // conn.setReadTimeout(10000 /* milliseconds *///); // conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestProperty("Content-Type", "application/json"); conn.setDoOutput(true); conn.setDoInput(true); conn.setRequestMethod("POST"); OutputStream out = new BufferedOutputStream(conn.getOutputStream()); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8")); writer.write(parameters.toString()); writer.close(); out.close(); int responseCode = conn.getResponseCode(); System.out.println(" Sending 'POST' request to URL : " + url); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); System.out.println("strngbuffr" + response.toString()); resp = response.toString(); } catch (Exception exception) { System.out.println("Exception: " + exception); } System.out.println("rsp"+ resp.toString()); return resp.toString(); } </code></pre> <p>I get the response code as 200, which means connection is okay however I get empty variables on PHP side, what can be wrong here? </p> <p>Earlier I was sending a JSON array too but just to test functonality I commented that out now I am only sending one variable <code>key as "key"</code></p> <p>Its amazing to see, this sample code works - sans the JSON array and the key value pairs: </p> <pre><code>private String sendPost(String url) throws Exception { String USER_AGENT = "Mozilla/5.0"; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); //add reuqest header con.setRequestMethod("POST"); con.setRequestProperty("User-Agent", USER_AGENT); con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); String urlParameters ="sn=C02G8416DRJM&amp;cn=&amp;locale=&amp;caller=&amp;num=12345"; // Send post request con.setDoOutput(true); DataOutputStream wr = new DataOutputStream(con.getOutputStream()); wr.writeBytes(urlParameters); wr.flush(); wr.close(); int responseCode = con.getResponseCode(); System.out.println(" Sending 'POST' request to URL : " + url); System.out.println("Post parameters : " + urlParameters); System.out.println("Response Code : " + responseCode); BufferedReader in = new BufferedReader( new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); //print result System.out.println("rvsp"+response.toString()); return response.toString(); } </code></pre> <p>So it boils down to replacing this:</p> <pre><code> JSONObject parameters = new JSONObject(); parameters.put("jsonArray", new JSONArray(Arrays.asList(makeJSON()))); parameters.put("key", getencryptkey()); </code></pre> <p>by this: </p> <pre><code>String urlParameters ="jArr="+makeJSON()+"Key="+getencryptkey(); </code></pre> <p>and I am still curious. </p> </div>

关于HttpURLConnection打开连接后,如何等待一段时间再关闭

各位大侠好,最近在做的一个工具时HttpURLConnection访问一个视频网站,然后如何让它停顿十几秒钟?而且这个停顿算不算在观看视频的?用 sleep 和 Timer 都不行,就好像直接跳过这两句了,其实要实现的功能就是:java 连接一个视频网站,然后模拟在看视频。请问各位大侠这个应该要怎么实现?

关于使用HttpURLConnection下载大文件的一些问题(UI卡顿) 求大神指导

下面是我的函数 private void getFile() { new Thread(new Runnable() { @Override public void run() { synchronized (this) { URL url = null; InputStream inputStream = null; FileOutputStream outputStream = null; long fileSize = 0; try { url = new URL(downloadUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setConnectTimeout(28000); connection.setRequestMethod("GET"); if (connection.getResponseCode() == 200) { inputStream = connection.getInputStream(); File file = new File(Environment.getExternalStorageDirectory() + "/" + directoriy, filename); outputStream = new FileOutputStream(file); fileSize = connection.getContentLength(); int length = 0; byte[] buffer = new byte[1024]; int downloadSize = 0; while ((length = inputStream.read(buffer)) != -1) { downloadSize = downloadSize + length; progress[0] = downloadSize / (float) fileSize; outputStream.write(buffer, 0, length); handler.sendEmptyMessage(INVALIDATE1); } outputStream.flush(); outputStream.close(); handler.sendEmptyMessage(LOAD_SUCCESS1); } } catch (MalformedURLException e) { handler.sendEmptyMessage(LOAD_ERROR1); e.printStackTrace(); e.getMessage(); try { if (inputStream != null) inputStream.close(); if (outputStream != null) outputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } catch (IOException e) { handler.sendEmptyMessage(LOAD_ERROR1); e.printStackTrace(); if (inputStream != null) try { inputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } if (outputStream != null) try { outputStream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } } }).start(); } 用上面的函数下载一个1个G的文件要改成POST方式吗?需要的话函数需要拿些改动呢,还有就是下载启动大文件之后对UI有很大的影响,列表直接卡住了,想请问用什么方法可以优化一下呢?

Java 通过HttpURLConnection获取URL接口的返回数据中含有少数民族语言变成了乱码

各位大神 private static String getJson(String url){ // String url = "http://data1.cnr.cn/minzu_hanyuzhuan/phpencode.php?word="+para; URL oldUrl; StringBuffer buffer = null; try { oldUrl = new URL(url); HttpURLConnection con = (HttpURLConnection) oldUrl.openConnection(); con.setRequestMethod("GET"); con.addRequestProperty("Content-Type", "application/json;charset=utf-8"); con.connect(); InputStream in = con.getInputStream(); BufferedReader bf=new BufferedReader(new InputStreamReader(in,"UTF-8")); buffer=new StringBuffer(); String line=""; while((line=bf.readLine())!=null){ buffer.append(line); } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ProtocolException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String json = buffer.toString(); return json; } 该方法得到的json字符串中的少数民族语言都是乱码,该怎么解决这个问题?

HttpURLConnection测试程序崩溃

今天照《第一行代码》第10章敲出来的HttpURLConnection测试程序运行之后一直闪退,求大神指点,小白拜谢! 错误日志如下: ![图片说明](https://img-ask.csdn.net/upload/201602/05/1454676432_247741.png) ![图片说明](https://img-ask.csdn.net/upload/201602/05/1454676448_254545.png) 代码如下: ``` package com.example.networktest; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import android.app.Activity; import android.app.ActionBar; import android.app.AlertDialog.Builder; import android.app.Fragment; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import android.os.Build; public class MainActivity extends Activity implements OnClickListener { public static final int SHOW_RESPONSE = 0; private TextView textView; private Button button; private Handler handler = new Handler() { public void handlerMessage(Message msg) { switch (msg.what) { case SHOW_RESPONSE: String response = (String) msg.obj; // 更新UI操作 textView.setText(response); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.fragment_main); textView = (TextView) findViewById(R.id.sendRequest); button = (Button) findViewById(R.id.responseText); button.setOnClickListener(this); } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v.getId() == R.id.sendRequest) { sendRequsetWithHttpURLConnection(); } } private void sendRequsetWithHttpURLConnection() { // 开启线程来发起网络请求 new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub HttpURLConnection connection = null; try { URL url = new URL("http://www.baidu.com"); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(8000); connection.setReadTimeout(8000); InputStream in = connection.getInputStream(); // 对获取到的输入流进行解析 BufferedReader reader = new BufferedReader( new InputStreamReader(in)); StringBuilder response = new StringBuilder(); String line ; while ((line=reader.readLine()) != null) { response.append(line); } // 发送返回结果 Message message = new Message(); message.what = SHOW_RESPONSE; message.obj = response.toString(); handler.sendMessage(message); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } } } }).start(); } } ```

C/C++学习指南全套教程

C/C++学习的全套教程,从基本语法,基本原理,到界面开发、网络开发、Linux开发、安全算法,应用尽用。由毕业于清华大学的业内人士执课,为C/C++编程爱好者的教程。

定量遥感中文版 梁顺林著 范闻捷译

这是梁顺林的定量遥感的中文版,由范闻捷等翻译的,是电子版PDF,解决了大家看英文费时费事的问题,希望大家下载看看,一定会有帮助的

YOLOv3目标检测实战:训练自己的数据集

YOLOv3是一种基于深度学习的端到端实时目标检测方法,以速度快见长。本课程将手把手地教大家使用labelImg标注和使用YOLOv3训练自己的数据集。课程分为三个小项目:足球目标检测(单目标检测)、梅西目标检测(单目标检测)、足球和梅西同时目标检测(两目标检测)。 本课程的YOLOv3使用Darknet,在Ubuntu系统上做项目演示。包括:安装Darknet、给自己的数据集打标签、整理自己的数据集、修改配置文件、训练自己的数据集、测试训练出的网络模型、性能统计(mAP计算和画出PR曲线)和先验框聚类。 Darknet是使用C语言实现的轻型开源深度学习框架,依赖少,可移植性好,值得深入探究。 除本课程《YOLOv3目标检测实战:训练自己的数据集》外,本人推出了有关YOLOv3目标检测的系列课程,请持续关注该系列的其它课程视频,包括: 《YOLOv3目标检测实战:交通标志识别》 《YOLOv3目标检测:原理与源码解析》 《YOLOv3目标检测:网络模型改进方法》 敬请关注并选择学习!

sql语句 异常 Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your

在我们开发的工程中,有时候会报 [Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ------ 这种异常 不用多想,肯定是我们的sql语句出现问题,下面...

浪潮集团 往年的软件类 笔试题 比较详细的哦

浪潮集团 往年的软件类 笔试题 比较详细的哦

2019 AI开发者大会

2019 AI开发者大会(AI ProCon 2019)是由中国IT社区CSDN主办的AI技术与产业年度盛会。多年经验淬炼,如今蓄势待发:2019年9月6-7日,大会将有近百位中美顶尖AI专家、知名企业代表以及千余名AI开发者齐聚北京,进行技术解读和产业论证。我们不空谈口号,只谈技术,诚挚邀请AI业内人士一起共铸人工智能新篇章!

I2c串口通信实现加速度传感器和FPGA的交流

此代码能实现加速度传感器与FPGA之间的交流,从而测出运动物体的加速度。

Python可以这样学(第一季:Python内功修炼)

董付国系列教材《Python程序设计基础》、《Python程序设计(第2版)》、《Python可以这样学》配套视频,讲解Python 3.5.x和3.6.x语法、内置对象用法、选择与循环以及函数设计与使用、lambda表达式用法、字符串与正则表达式应用、面向对象编程、文本文件与二进制文件操作、目录操作与系统运维、异常处理结构。

微信公众平台开发入门

本套课程的设计完全是为初学者量身打造,课程内容由浅入深,课程讲解通俗易懂,代码实现简洁清晰。通过本课程的学习,学员能够入门微信公众平台开发,能够胜任企业级的订阅号、服务号、企业号的应用开发工作。 通过本课程的学习,学员能够对微信公众平台有一个清晰的、系统性的认识。例如,公众号是什么,它有什么特点,它能做什么,怎么开发公众号。 其次,通过本课程的学习,学员能够掌握微信公众平台开发的方法、技术和应用实现。例如,开发者文档怎么看,开发环境怎么搭建,基本的消息交互如何实现,常用的方法技巧有哪些,真实应用怎么开发。

机器学习初学者必会的案例精讲

通过六个实际的编码项目,带领同学入门人工智能。这些项目涉及机器学习(回归,分类,聚类),深度学习(神经网络),底层数学算法,Weka数据挖掘,利用Git开源项目实战等。

eclipseme 1.7.9

eclipse 出了新的eclipseme插件,官方有下载,但特慢,我都下了大半天(可能自己网速差)。有急需要的朋友可以下哦。。。

Spring Boot -01- 快速入门篇(图文教程)

Spring Boot -01- 快速入门篇 今天开始不断整理 Spring Boot 2.0 版本学习笔记,大家可以在博客看到我的笔记,然后大家想看视频课程也可以到【慕课网】手机 app,去找【Spring Boot 2.0 深度实践】的课程,令人开心的是,课程完全免费! 什么是 Spring Boot? Spring Boot 是由 Pivotal 团队提供的全新框架。Spring Boot...

HoloLens2开发入门教程

本课程为HoloLens2开发入门教程,讲解部署开发环境,安装VS2019,Unity版本,Windows SDK,创建Unity项目,讲解如何使用MRTK,编辑器模拟手势交互,打包VS工程并编译部署应用到HoloLens上等。

最简单的倍频verilog程序(Quartus II)

一个工程文件 几段简单的代码 一个输入一个输出(50Mhz倍频到100Mhz)

计算机组成原理实验教程

西北工业大学计算机组成原理实验课唐都仪器实验帮助,同实验指导书。分为运算器,存储器,控制器,模型计算机,输入输出系统5个章节

4小时玩转微信小程序——基础入门与微信支付实战

这是一个门针对零基础学员学习微信小程序开发的视频教学课程。课程采用腾讯官方文档作为教程的唯一技术资料来源。杜绝网络上质量良莠不齐的资料给学员学习带来的障碍。 视频课程按照开发工具的下载、安装、使用、程序结构、视图层、逻辑层、微信小程序等几个部分组织课程,详细讲解整个小程序的开发过程

面试了一个 31 岁程序员,让我有所触动,30岁以上的程序员该何去何从?

最近面试了一个31岁8年经验的程序猿,让我有点感慨,大龄程序猿该何去何从。

基于RSA通信密钥分发的加密通信

基于RSA通信密钥分发的加密通信,采用pycrypto中的RSA、AES模块实现

不同变质程度煤尘爆炸残留气体特征研究

为分析不同变质程度煤尘爆炸残留气体成分的特征规律,利用水平管道煤尘爆炸实验装置进行了贫瘦煤、肥煤、气煤、长焰煤4种不同变质程度的煤尘爆炸实验,研究了不同变质程度煤尘爆炸后气体残留物含量的差异,并对气体

设计模式(JAVA语言实现)--20种设计模式附带源码

课程亮点: 课程培训详细的笔记以及实例代码,让学员开始掌握设计模式知识点 课程内容: 工厂模式、桥接模式、组合模式、装饰器模式、外观模式、享元模式、原型模型、代理模式、单例模式、适配器模式 策略模式、模板方法模式、观察者模式、迭代器模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式 课程特色: 笔记设计模式,用笔记串连所有知识点,让学员从一点一滴积累,学习过程无压力 笔记标题采用关键字标识法,帮助学员更加容易记住知识点 笔记以超链接形式让知识点关联起来,形式知识体系 采用先概念后实例再应用方式,知识点深入浅出 提供授课内容笔记作为课后复习以及工作备查工具 部分图表(电脑PC端查看):

MySQL数据库面试题(2020最新版)

文章目录数据库基础知识为什么要使用数据库什么是SQL?什么是MySQL?数据库三大范式是什么mysql有关权限的表都有哪几个MySQL的binlog有有几种录入格式?分别有什么区别?数据类型mysql有哪些数据类型引擎MySQL存储引擎MyISAM与InnoDB区别MyISAM索引与InnoDB索引的区别?InnoDB引擎的4大特性存储引擎选择索引什么是索引?索引有哪些优缺点?索引使用场景(重点)...

软件测试2小时入门

本课程内容系统、全面、简洁、通俗易懂,通过2个多小时的介绍,让大家对软件测试有个系统的理解和认识,具备基本的软件测试理论基础。 主要内容分为5个部分: 1 软件测试概述,了解测试是什么、测试的对象、原则、流程、方法、模型;&nbsp; 2.常用的黑盒测试用例设计方法及示例演示;&nbsp; 3 常用白盒测试用例设计方法及示例演示;&nbsp; 4.自动化测试优缺点、使用范围及示例‘;&nbsp; 5.测试经验谈。

几率大的Redis面试题(含答案)

本文的面试题如下: Redis 持久化机制 缓存雪崩、缓存穿透、缓存预热、缓存更新、缓存降级等问题 热点数据和冷数据是什么 Memcache与Redis的区别都有哪些? 单线程的redis为什么这么快 redis的数据类型,以及每种数据类型的使用场景,Redis 内部结构 redis的过期策略以及内存淘汰机制【~】 Redis 为什么是单线程的,优点 如何解决redis的并发竞争key问题 Red...

手把手实现Java图书管理系统(附源码)

【超实用课程内容】 本课程演示的是一套基于Java的SSM框架实现的图书管理系统,主要针对计算机相关专业的正在做毕设的学生与需要项目实战练习的java人群。详细介绍了图书管理系统的实现,包括:环境搭建、系统业务、技术实现、项目运行、功能演示、系统扩展等,以通俗易懂的方式,手把手的带你从零开始运行本套图书管理系统,该项目附带全部源码可作为毕设使用。 【课程如何观看?】 PC端:https://edu.csdn.net/course/detail/27513 移动端:CSDN 学院APP(注意不是CSDN APP哦) 本课程为录播课,课程2年有效观看时长,大家可以抓紧时间学习后一起讨论哦~ 【学员专享增值服务】 源码开放 课件、课程案例代码完全开放给你,你可以根据所学知识,自行修改、优化

jsp+servlet入门项目实例

jsp+servlet实现班级信息管理项目

winfrom中嵌套html,跟html的交互

winfrom中嵌套html,跟html的交互,源码就在里面一看就懂,很简单

Java面试题大全(2020版)

发现网上很多Java面试题都没有答案,所以花了很长时间搜集整理出来了这套Java面试题大全,希望对大家有帮助哈~ 本套Java面试题大全,全的不能再全,哈哈~ 一、Java 基础 1. JDK 和 JRE 有什么区别? JDK:Java Development Kit 的简称,java 开发工具包,提供了 java 的开发环境和运行环境。 JRE:Java Runtime Environ...

python实现数字水印添加与提取及鲁棒性测试(GUI,基于DCT,含测试图片)

由python写的GUI,可以实现数字水印的添加与提取,提取是根据添加系数的相关性,实现了盲提取。含有两种攻击测试方法(高斯低通滤波、高斯白噪声)。基于python2.7,watermark.py为主

Xshell6完美破解版,亲测可用

Xshell6破解版,亲测可用,分享给大家。直接解压即可使用

你连存活到JDK8中著名的Bug都不知道,我怎么敢给你加薪

CopyOnWriteArrayList.java和ArrayList.java,这2个类的构造函数,注释中有一句话 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 public ArrayList(Collection&lt;? ...

相关热词 c# dbml文件 修改 c#遍历tree c# 能够控制单片机 c#对象写入数据库 c# 添加activex c#2005 json c# 数据库在云端 c# 字符串移位加密 c#禁用滚轮 c#实体类list去重复
立即提问