本文目錄一覽:
- 1、怎麼php發送get請求給Java,然後返回想要的具體參數
- 2、java中get請求和post請求分別請求的對象類型是什麼,什麼不一樣
- 3、java中怎樣用post,get,put請求
- 4、JAVA中Get和Post請求的區別收集整理
- 5、java做手機端後台,如何接受get請求參數
怎麼php發送get請求給Java,然後返回想要的具體參數
curl請求java介面,介面返回值後進行相關操作,給你貼一個curl的代碼
function ihttp_request($url, $post = ”, $extra = array(), $timeout = 60) {
$urlset = parse_url($url);
if (empty($urlset[‘path’])) {
$urlset[‘path’] = ‘/’;
}
if (!empty($urlset[‘query’])) {
$urlset[‘query’] = “?{$urlset[‘query’]}”;
}
if (empty($urlset[‘port’])) {
$urlset[‘port’] = $urlset[‘scheme’] == ‘https’ ? ‘443’ : ’80’;
}
if (strexists($url, ‘https://’) !extension_loaded(‘openssl’)) {
if (!extension_loaded(“openssl”)) {
message(‘請開啟您PHP環境的openssl’);
}
}
if (function_exists(‘curl_init’) function_exists(‘curl_exec’)) {
$ch = curl_init();
if (ver_compare(phpversion(), ‘5.6’) = 0) {
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
}
if (!empty($extra[‘ip’])) {
$extra[‘Host’] = $urlset[‘host’];
$urlset[‘host’] = $extra[‘ip’];
unset($extra[‘ip’]);
}
curl_setopt($ch, CURLOPT_URL, $urlset[‘scheme’] . ‘://’ . $urlset[‘host’] . ($urlset[‘port’] == ’80’ ? ” : ‘:’ . $urlset[‘port’]) . $urlset[‘path’] . $urlset[‘query’]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
@curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
@curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
if ($post) {
if (is_array($post)) {
$filepost = false;
foreach ($post as $name = $value) {
if ((is_string($value) substr($value, 0, 1) == ‘@’) || (class_exists(‘CURLFile’) $value instanceof CURLFile)) {
$filepost = true;
break;
}
}
if (!$filepost) {
$post = http_build_query($post);
}
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
}
if (!empty($GLOBALS[‘_W’][‘config’][‘setting’][‘proxy’])) {
$urls = parse_url($GLOBALS[‘_W’][‘config’][‘setting’][‘proxy’][‘host’]);
if (!empty($urls[‘host’])) {
curl_setopt($ch, CURLOPT_PROXY, “{$urls[‘host’]}:{$urls[‘port’]}”);
$proxytype = ‘CURLPROXY_’ . strtoupper($urls[‘scheme’]);
if (!empty($urls[‘scheme’]) defined($proxytype)) {
curl_setopt($ch, CURLOPT_PROXYTYPE, constant($proxytype));
} else {
curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
}
if (!empty($GLOBALS[‘_W’][‘config’][‘setting’][‘proxy’][‘auth’])) {
curl_setopt($ch, CURLOPT_PROXYUSERPWD, $GLOBALS[‘_W’][‘config’][‘setting’][‘proxy’][‘auth’]);
}
}
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSLVERSION, 1);
if (defined(‘CURL_SSLVERSION_TLSv1’)) {
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1);
}
curl_setopt($ch, CURLOPT_USERAGENT, ‘Mozilla/5.0 (Windows NT 6.1; WOW64; rv:9.0.1) Gecko/20100101 Firefox/9.0.1’);
if (!empty($extra) is_array($extra)) {
$headers = array();
foreach ($extra as $opt = $value) {
if (strexists($opt, ‘CURLOPT_’)) {
curl_setopt($ch, constant($opt), $value);
} elseif (is_numeric($opt)) {
curl_setopt($ch, $opt, $value);
} else {
$headers[] = “{$opt}: {$value}”;
}
}
if (!empty($headers)) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
}
}
$data = curl_exec($ch);
$status = curl_getinfo($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
curl_close($ch);
if ($errno || empty($data)) {
return error(1, $error);
} else {
return ihttp_response_parse($data);
}
}
$method = empty($post) ? ‘GET’ : ‘POST’;
$fdata = “{$method} {$urlset[‘path’]}{$urlset[‘query’]} HTTP/1.1\r\n”;
$fdata .= “Host: {$urlset[‘host’]}\r\n”;
if (function_exists(‘gzdecode’)) {
$fdata .= “Accept-Encoding: gzip, deflate\r\n”;
}
$fdata .= “Connection: close\r\n”;
if (!empty($extra) is_array($extra)) {
foreach ($extra as $opt = $value) {
if (!strexists($opt, ‘CURLOPT_’)) {
$fdata .= “{$opt}: {$value}\r\n”;
}
}
}
$body = ”;
if ($post) {
if (is_array($post)) {
$body = http_build_query($post);
} else {
$body = urlencode($post);
}
$fdata .= ‘Content-Length: ‘ . strlen($body) . “\r\n\r\n{$body}”;
} else {
$fdata .= “\r\n”;
}
if ($urlset[‘scheme’] == ‘https’) {
$fp = fsockopen(‘ssl://’ . $urlset[‘host’], $urlset[‘port’], $errno, $error);
} else {
$fp = fsockopen($urlset[‘host’], $urlset[‘port’], $errno, $error);
}
stream_set_blocking($fp, true);
stream_set_timeout($fp, $timeout);
if (!$fp) {
return error(1, $error);
} else {
fwrite($fp, $fdata);
$content = ”;
while (!feof($fp))
$content .= fgets($fp, 512);
fclose($fp);
return ihttp_response_parse($content, true);
}
}
java中get請求和post請求分別請求的對象類型是什麼,什麼不一樣
1. get 是從伺服器上獲取數據,post 是向伺服器傳送數據。 get 請求返回 request – URI 所指出的任意信息。
Post 請求用來發送電子郵件、新聞或發送能由交互用戶填寫的表格。這是唯一需要在請求中發送body的請求。使用Post請求時需要在報文首部 Content – Length 欄位中指出body的長度。
2. get 是把參數數據隊列加到提交表單的ACTION屬性所指的URL中,值和表單內各個欄位一一對應,在URL中可以看到。post是通過HTTP post機制,將表單內各個欄位與其內容放置在HTML HEADER內一起傳送到ACTION屬性所指的URL地址,用戶看不到這個過程。
3. 對於 get 方式,伺服器端用Request.QueryString獲取變數的值,對於 post 方式,伺服器端用Request.Form獲取提交的數據。
4. get 傳送的數據量較小,不能大於2KB。post 傳送的數據量較大,一般被默認為不受限制。但理論上,IIS4中最大量為80KB,IIS5中為100KB。 用IIS過濾器的只接受get參數,所以一般大型搜索引擎都是用get方式。
5. get 安全性非常低,post 安全性相對較高。如果這些數據是中文數據而且是非敏感數據,那麼使用 get;如果用戶輸入的數據不是中文字元而且包含敏感數據,那麼還是使用 post 為好。
java中怎樣用post,get,put請求
java中用post,get,put請求方法:
public static String javaHttpGet(String url,String charSet){
String resultData = null;
try {
URL pathUrl = new URL(url); //創建一個URL對象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection(); //打開一個HttpURLConnection連接
urlConnect.setConnectTimeout(30000); // 設置連接超時時間
urlConnect.connect();
if (urlConnect.getResponseCode() == 200) { //請求成功
resultData = readInputStream(urlConnect.getInputStream(), charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error(“URL出錯!”, e);
} catch (IOException e) {
LogL.getInstance().getLog().error(“讀取數據流出錯!”, e);
}
return resultData;
}
public static String javaHttpPost(String url,MapString,Object map,String charSet){
String resultData=null;
StringBuffer params = new StringBuffer();
try {
IteratorEntryString, Object ir = map.entrySet().iterator();
while (ir.hasNext()) {
Map.EntryString, Object entry = (Map.EntryString, Object) ir.next();
params.append(URLEncoder.encode(entry.getKey(),charSet) + “=” + URLEncoder.encode(entry.getValue().toString(), charSet) + “”);
}
byte[] postData = params.deleteCharAt(params.length()).toString().getBytes();
URL pathUrl = new URL(url); //創建一個URL對象
HttpURLConnection urlConnect = (HttpURLConnection) pathUrl.openConnection();
urlConnect.setConnectTimeout(30000); // 設置連接超時時間
urlConnect.setDoOutput(true); //post請求必須設置允許輸出
urlConnect.setUseCaches(false); //post請求不能使用緩存
urlConnect.setRequestMethod(“POST”); //設置post方式請求
urlConnect.setInstanceFollowRedirects(true);
urlConnect.setRequestProperty(“Content-Type”,”application/x-www-form-urlencoded; charset=”+charSet);// 配置請求Content-Type
urlConnect.connect(); // 開始連接
DataOutputStream dos = new DataOutputStream(urlConnect.getOutputStream()); // 發送請求參數
dos.write(postData);
dos.flush();
dos.close();
if (urlConnect.getResponseCode() == 200) { //請求成功
resultData = readInputStream(urlConnect.getInputStream(),charSet);
}
} catch (MalformedURLException e) {
LogL.getInstance().getLog().error(“URL出錯!”, e);
} catch (IOException e) {
LogL.getInstance().getLog().error(“讀取數據流出錯!”, e);
} catch (Exception e) {
LogL.getInstance().getLog().error(“POST出錯!”, e);
}
return resultData;
}
JAVA中Get和Post請求的區別收集整理
Get:是以實體的方式得到由請求URI所指定資源的信息,如果請求URI只是一個數據產生過程,那麼最終要在響應實體中返回的是處理過程的結果所指向的資源,而不是處理過程的描述。
Post:用來向目的伺服器發出請求,要求它接受被附在請求後的實體,並把它當作請求隊列中請求URI所指定資源的附加新子項,Post被設計成用統一的方法實現下列功能:
1:對現有資源的解釋
2:向電子公告欄、新聞組、郵件列表或類似討論組發信息。
3:提交數據塊
4:通過附加操作來擴展資料庫
從上面描述可以看出,Get是向伺服器發索取數據的一種請求;而Post是向伺服器提交數據的一種請求,要提交的數據位於信息頭後面的實體中。
java做手機端後台,如何接受get請求參數
package com.weixin.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.CookiePolicy;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
//import bsh.ParseException;
import com.google.gson.Gson;
/**
* TODO
* @Version 1.0
*/
public class HttpClients {
/** UTF-8 */
private static final String UTF_8 = “UTF-8”;
/** 日誌記錄tag */
private static final String TAG = “HttpClients”;
/** 用戶host */
private static String proxyHost = “”;
/** 用戶埠 */
private static int proxyPort = 80;
/** 是否使用用戶埠 */
private static boolean useProxy = false;
/** 連接超時 */
private static final int TIMEOUT_CONNECTION = 60000;
/** 讀取超時 */
private static final int TIMEOUT_SOCKET = 60000;
/** 重試3次 */
private static final int RETRY_TIME = 3;
/**
* @param url
* @param requestData
* @return
*/
public String doHtmlPost(HttpClient httpClient,HttpPost httpPost )
{
String responseBody = null;
int statusCode = -1;
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
Header lastHeader = httpResponse.getLastHeader(“Set-Cookie”);
if(null != lastHeader)
{
httpPost.setHeader(“cookie”, lastHeader.getValue());
}
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println(“HTTP” + ” ” + “HttpMethod failed: ” + httpResponse.getStatusLine());
}
InputStream is = httpResponse.getEntity().getContent();
responseBody = getStreamAsString(is, HTTP.UTF_8);
} catch (Exception e) {
// 發生網路異常
e.printStackTrace();
} finally {
// httpClient.getConnectionManager().shutdown();
// httpClient = null;
}
return responseBody;
}
/**
*
* 發起網路請求
*
* @param url
* URL
* @param requestData
* requestData
* @return INPUTSTREAM
* @throws AppException
*/
public static String doPost(String url, String requestData) throws Exception {
String responseBody = null;
HttpPost httpPost = null;
HttpClient httpClient = null;
int statusCode = -1;
int time = 0;
do {
try {
httpPost = new HttpPost(url);
httpClient = getHttpClient();
// 設置HTTP POST請求參數必須用NameValuePair對象
ListBasicNameValuePair params = new ArrayListBasicNameValuePair();
params.add(new BasicNameValuePair(“param”, requestData));
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
// 設置HTTP POST請求參數
httpPost.setEntity(entity);
HttpResponse httpResponse = httpClient.execute(httpPost);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println(“HTTP” + ” ” + “HttpMethod failed: ” + httpResponse.getStatusLine());
}
InputStream is = httpResponse.getEntity().getContent();
responseBody = getStreamAsString(is, HTTP.UTF_8);
break;
} catch (UnsupportedEncodingException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();
} catch (ClientProtocolException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();
} catch (IOException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生網路異常
e.printStackTrace();
} catch (Exception e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生網路異常
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
} while (time RETRY_TIME);
return responseBody;
}
/**
*
* 將InputStream 轉化為String
*
* @param stream
* inputstream
* @param charset
* 字符集
* @return
* @throws IOException
*/
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset), 8192);
StringWriter writer = new StringWriter();
char[] chars = new char[8192];
int count = 0;
while ((count = reader.read(chars)) 0) {
writer.write(chars, 0, count);
}
return writer.toString();
} finally {
if (stream != null) {
stream.close();
}
}
}
/**
* 得到httpClient
*
* @return
*/
public HttpClient getHttpClient1() {
final HttpParams httpParams = new BasicHttpParams();
if (useProxy) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, “http”);
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams, true);
final String userAgent = “Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.14) Gecko/20110218 Firefox/3.6.14”;
HttpProtocolParams.setUserAgent(httpParams, userAgent);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.RFC_2109);
HttpProtocolParams.setUseExpectContinue(httpParams, false);
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}
/**
*
* 得到httpClient
*
* @return
*/
private static HttpClient getHttpClient() {
final HttpParams httpParams = new BasicHttpParams();
if (useProxy) {
HttpHost proxy = new HttpHost(proxyHost, proxyPort, “http”);
httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
}
HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_CONNECTION);
HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_SOCKET);
HttpClientParams.setRedirecting(httpParams, true);
final String userAgent = “Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-CN; rv:1.9.2.14) Gecko/20110218 Firefox/3.6.14”;
HttpProtocolParams.setUserAgent(httpParams, userAgent);
HttpProtocolParams.setVersion(httpParams, HttpVersion.HTTP_1_1);
HttpClientParams.setCookiePolicy(httpParams, CookiePolicy.BROWSER_COMPATIBILITY);
HttpProtocolParams.setUseExpectContinue(httpParams, false);
HttpClient client = new DefaultHttpClient(httpParams);
return client;
}
/**
* 列印返回內容
* @param response
* @throws ParseException
* @throws IOException
*/
public static void showResponse(String str) throws Exception {
Gson gson = new Gson();
MapString, Object map = (MapString, Object) gson.fromJson(str, Object.class);
String value = (String) map.get(“data”);
//String decodeValue = Des3Request.decode(value);
//System.out.println(decodeValue);
//logger.debug(decodeValue);
}
/**
*
* 發起網路請求
*
* @param url
* URL
* @param requestData
* requestData
* @return INPUTSTREAM
* @throws AppException
*/
public static String doGet(String url) throws Exception {
String responseBody = null;
HttpGet httpGet = null;
HttpClient httpClient = null;
int statusCode = -1;
int time = 0;
do {
try {
httpGet = new HttpGet(url);
httpClient = getHttpClient();
HttpResponse httpResponse = httpClient.execute(httpGet);
statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println(“HTTP” + ” ” + “HttpMethod failed: ” + httpResponse.getStatusLine());
}
InputStream is = httpResponse.getEntity().getContent();
responseBody = getStreamAsString(is, HTTP.UTF_8);
break;
} catch (UnsupportedEncodingException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();
} catch (ClientProtocolException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生致命的異常,可能是協議不對或者返回的內容有問題
e.printStackTrace();
} catch (IOException e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生網路異常
e.printStackTrace();
} catch (Exception e) {
time++;
if (time RETRY_TIME) {
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
}
continue;
}
// 發生網路異常
e.printStackTrace();
} finally {
httpClient.getConnectionManager().shutdown();
httpClient = null;
}
} while (time RETRY_TIME);
return responseBody;
}
}
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/183220.html